-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmovingCount.cpp
More file actions
55 lines (46 loc) · 1.43 KB
/
movingCount.cpp
File metadata and controls
55 lines (46 loc) · 1.43 KB
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
// 13 机器人🤖的运动范围
#include "array_util.h"
using namespace std;
// 辅助函数 计算各十进制位之和
int getDigitSum(int num)
{
assert(num >= 0);
int sum = 0;
while (num) {
sum += num % 10;
num /= 10;
}
return sum;
}
int check(int threshold, int rows, int cols, int row, int col, bool* visited)
{
if (row >= 0 && row < rows && col >= 0 && col < cols
&& getDigitSum(row) + getDigitSum(col) <= threshold
&& !visited[row + cols + col])
return true;
return false;
}
int movingCountCore(int threshold, int rows, int cols, int row, int col, bool* visited)
{
int count = 0;
if (check(threshold, rows, cols, row, col, visited)) {
visited[row + cols + col] = true;
count = 1 + movingCountCore(threshold, rows, cols, row - 1, col, visited)
+ movingCountCore(threshold, rows, cols, row, col - 1, visited)
+ movingCountCore(threshold, rows, cols, row + 1, col, visited)
+ movingCountCore(threshold, rows, cols, row, col + 1, visited);
}
return count;
}
int movingCount(int threshold, int rows, int cols)
{
if (threshold < 0 || rows <= 0 || cols <= 0)
return 0;
bool* visited = new bool[rows * cols];
for (int i = 0; i < rows * cols; i++) {
visited[i] = false;
}
int count = movingCountCore(threshold, rows, cols, 0, 0, visited);
delete[] visited;
return count;
}