CodingInterview-机器人的运动范围

这道题和 上一道题(矩阵中的路径) 思路很类似,主要还是回溯法,只是条件稍微变了一些。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
private:
int count;
int threshold;
int rows;
int cols;
bool* visited;
public:
int movingCount(int threshold, int rows, int cols)
{
count=0;
this->threshold=threshold;
this->rows=rows;
this->cols=cols;
visited=new bool[rows*cols];
memset(visited,false,rows*cols);
search(0,0);
return count;
}
void search(int row,int col){
if(row<0 || col<0 || row>=rows || col>=cols) return;
if(visited[row*cols+col]) return;
visited[row*cols+col]=true;
if(!isValid(row,col)) return;
count++;
search(row-1,col);
search(row+1,col);
search(row,col-1);
search(row,col+1);
}
bool isValid(int row,int col){
int sum=0;
while(row>0){
sum+=row%10;
row/=10;
}
while(col>0){
sum+=col%10;
col/=10;
}
return sum<=threshold;
}
};