There is a M-row and N-column squares on the ground. A robot moves from the grid of coordinates 0,0, each time only to the left, right, upper and lower four directions, but cannot enter the coordinates of the row and column coordinates of the sum of the squares greater than K. For example, when K is 18 o'clock, the robot can enter the square (35,37) because 3+5+3+7 = 18. However, it cannot enter the grid (35,38) because 3+5+3+8 = 19. How many grids can the robot reach?
Class Solution {
Public
int getsum (int i)
{
int sum=0;
while (i)
{
sum+=i%10;
I=I/10;
}
return sum;
}
int getnum (int i,int j,int rows,int cols,int threshold,int **flag)
{
if (i<0 | | i>=rows | | j<0 | | j>=cols | | getsum (i) +getsum (j) >threshold | | flag[i][j]==1)//not eligible, return 0
return 0;
Flag[i][j]=1;
Return Getnum (I-1,j,rows,cols,threshold,flag) +getnum (I+1,j,rows,cols,threshold,flag) +
Getnum (I,j-1,rows,cols,threshold,flag) +getnum (I,j+1,rows,cols,threshold,flag) +1;
}
int movingcount (int threshold, int rows, int cols)
{
int **flag=new Int*[rows];
for (int i=0;i<rows;i++)
Flag[i]=new Int[cols];
Return Getnum (0,0,rows,cols,threshold,flag);
}
};
How many squares can a robot walk?