题目描述 地上有一个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。
#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;
}
}
};