Title Description
ground there is a grid of m rows and n columns. A robot moves from the grid coordinates 0,0, every time only left, right, upper, lower four directions a cell, but can not enter the row and column coordinates of the grid is greater than the sum of the number of bits k. For example, when k is 18, the robot can enter the box (35, 37), because 3 + 3 + 5 + 7 = 18. However, it can not enter the box (35, 38), because 3 + 3 + 5 + 8 = 19. Will the robot be able to reach the number of lattice?
Solution:
1, depth-first search
2, four directions
3, similar to a question on
class Solution {
public:
int sum(int num)
{
int s = 0;
while(num)
{
s += num%10;
num /= 10;
}
return s;
}
int DFS(int threshold, int r, int c, int rows, int cols, bool*vis)
{
int cnt = 0;
if(r>=0 && r<rows && c>=0 && c<cols && (sum(r)+sum(c)) <= threshold && !vis[r*cols+c])
{
vis[r*cols+c] = 1;
cnt = 1 + DFS(threshold, r+1, c, rows, cols, vis)
+ DFS(threshold, r-1, c, rows, cols, vis)
+ DFS(threshold, r, c+1, rows, cols, vis)
+ DFS(threshold, r, c-1, rows, cols, vis);
}
return cnt;
}
int movingCount(int threshold, int rows, int cols)
{
bool* vis = new bool[rows*cols];
memset(vis, 0, rows*cols);
int cnt = DFS(threshold, 0, 0, rows, cols, vis);
return cnt;
}
};