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
|
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
int count = 0;
bool *flag = new bool[rows * cols]();
count = move(threshold,rows,cols,0,0,flag);
return count;
}
// 判断是否能移动
bool isMove(int rows,int cols,int i,int j,int threshold,bool *flag)
{
if(i >= 0 && j >= 0&& i < rows && j < cols && !flag[i * cols + j] && getNum(i) + getNum(j) <= threshold) return true;
return false;
}
int getNum(int k)
{
int res = 0;
while(k > 0 )
{
res += k % 10;
k /= 10;
}
return res;
}
// 递归的移动函数
int move(int threshold,int rows,int cols,int i,int j,bool *flag)
{
int count = 0;
if(isMove(rows,cols,i,j,threshold,flag))
{
flag[i * cols + j] = true;
count = 1 + move(threshold,rows,cols,i-1,j,flag)
+ move(threshold,rows,cols,i+1,j,flag)
+ move(threshold,rows,cols,i,j - 1,flag)
+ move(threshold,rows,cols,i,j + 1,flag);
}
return count;
}
};
|