0%

机器人的运动范围

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

回溯,DFS/BFS

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
44
45
46
47
48
49
50
51
52
53
54
55
56
const int xMove[] = {0, 1, 0, -1};
const int yMove[] = {-1, 0, 1, 0};

class Solution {
public:
int getSum(int n)
{
int sum = 0;
while (n > 0)
{
int left = n / 10;
sum += n - 10 * left;
n = left;
}
return sum;
}
int movingCount(int threshold, int rows, int cols)
{
if (threshold <= 0 || rows < 1 || cols < 1)
{
return 0;
}
else
{
bool isAdded[127][127] = {false};
int area = 1;
int xRoute[65535], yRoute[65535];
int peak = 0;
xRoute[0] = 0;
yRoute[0] = 0;
isAdded[0][0] = true;
while (peak >= 0)
{
int x = xRoute[peak];
int y = yRoute[peak];
peak--;
for (int i = 0; i < 4; i++)
{
x += xMove[i];
y += yMove[i];
if (x >= 0 && x < cols && y >= 0 && y < rows && getSum(x) + getSum(y) <= threshold && !isAdded[x][y])
{
isAdded[x][y] = true;
peak++;
xRoute[peak] = x;
yRoute[peak] = y;
area++;
}
x -= xMove[i];
y -= yMove[i];
}
}
return area;
}
}
};