前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指offer——机器人的运动范围

剑指offer——机器人的运动范围

作者头像
AI那点小事
发布2020-04-18 00:42:26
3540
发布2020-04-18 00:42:26
举报
文章被收录于专栏:AI那点小事AI那点小事

概述

题目描述 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?


思路

这是典型的一道dfs的题。首先初始化访问数组isvisited全为0,计算器cnt为0,之后首先判断该点(row,col)的是否在坐标范围内且是未被访问,如果是那么就将cnt加1,之后isvisited[row][col] = 1,之后依次按左右上下的顺序遍历周围4个点并进行dfs;否则直接返回return。


C++ AC代码

代码语言:javascript
复制
#include <iostream>
#include <cstring> 
using namespace std;

class Solution {
    private:
        int** isvisited;
        int cnt;
        int Rows;
        int Cols;
        int Threshold;
    public:
        int movingCount(int threshold, int rows, int cols){
            this->cnt = 0;
            this->Rows = rows;
            this->Cols = cols; 
            this->Threshold = threshold;
            isvisited = new int*[rows+1];
            for(int i = 0 ; i < rows+1 ; i++){
                isvisited[i] = new int[cols+1];
                memset(isvisited[i],0,sizeof(isvisited[0][0])*(cols+1));
            }
            int move[4][2] = {{-1,0},{1,0},{0,1},{0,-1}};
            this->dfs(0,0,move);
            return this->cnt;
        }

        bool check(int row,int col){
            if(row < 0 || row >= this->Rows || col < 0 || col >= this->Cols){
                return false;
            }else{
                int sum1 = this->Caculate(row);
                int sum2 = this->Caculate(col);
                if(sum1+sum2 <= this->Threshold){
                    return true;
                }else{
                    return false;
                }
            }
        }

        int Caculate(int num){
            int sum = 0;
            while(num != 0){
                sum += num % 10;
                num /= 10;
            }
            return sum;
        }

        void dfs(int row,int col,int move[4][2]){
            if(this->check(row,col) && !this->isvisited[row][col]){
                this->cnt++;
                this->isvisited[row][col] = 1;
                for(int i = 0 ; i < 4 ; i++){
                    int r = row+move[i][0];
                    int c = col+move[i][1];
                    this->dfs(r,c,move);
                }
            }else{
                return;
            }
        }
}; 

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
  • 思路
  • C++ AC代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档