-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmovingCount.cpp
More file actions
76 lines (67 loc) · 1.85 KB
/
movingCount.cpp
File metadata and controls
76 lines (67 loc) · 1.85 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
int movingCount(int m, int n, int k)
{
int movingCountCore(int threshold, int rows, int cols, int i, int j, bool *visited);
int rows = m, cols = n;
int threshold = k;
if (threshold < 0|| rows < 0 || cols < 0)
{
return 0;
}
bool *visited = new bool[rows * cols];
memset(visited, 0, rows * cols);
// for (int i = 0; i < rows * cols; i++)
// {
// visited[i] = false;
// }
int count = movingCountCore(threshold, rows, cols, 0, 0, visited);
return count;
}
int movingCountCore(int threshold, int rows, int cols, int i, int j, bool *visited)
{
bool check(int threshold, int rows, int cols, int i , int j, bool *visited);
int count = 0;
if (check(threshold, rows, cols, i, j, visited))
{
visited[i * cols + j] = true;
int one = movingCountCore(threshold,rows, cols, i - 1, j, visited);
int two = movingCountCore(threshold,rows, cols, i, j - 1, visited);
int three = movingCountCore(threshold, rows, cols, i + 1, j, visited);
int four = movingCountCore(threshold, rows, cols, i, j + 1,visited);
count = 1 + one + two + three + four;
}
return count;
}
bool check(int threshold, int rows, int cols, int i , int j, bool *visited)
{
int getSum(int row, int col);
if (i >= 0 && i < rows && j >= 0 && j < cols && getSum(i ,j) <= threshold && !visited[i * cols + j])
{
return true;
}
return false;
}
int getSum(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;
}
int main()
{
int row = 2, col = 3, threshold = 1;
printf("%d",movingCount(row,col,threshold));
return 0;
}