The range of motion of the robot

Topic description

There is a square with m rows and n columns on the ground. A robot starts to move from the grid of coordinates 0 and 0, and can only move one grid in four directions: left, right, up and down at a time, but cannot enter the grid where the sum of the digits of the row and column coordinates is greater than k. For example, when k is 18, the robot is able to enter square (35,37) because 3+5+3+7 = 18. However, it cannot go into square (35,38) because 3+5+3+8 = 19. How many squares can the robot reach?
my code:
 1 class Solution {
 2 public:
 3     int Bsum(int num)
 4     {
 5         int sum = 0;
 6         while(num)
 7         {
 8             sum += num%10; 
 9             num = num/10; 
10         }
11         return sum;
12     }
13     int movingCount(int threshold, int rows, int cols)
14     {
15         int *matrix = new int[rows*cols];
16         for(int i = 0; i < rows*cols; i++)//初始化
17                 matrix[i] = 0;
18         return Count(threshold,matrix,rows,cols,0,0);
19     }
20     int Count(int threshold,int* matrix, int rows, int cols,int i, int j)
21     {
22         int sum = 0;
23         if(i >= 0&& j >= 0 && i < rows &&j < cols
24            &&  Bsum(i)+Bsum(j) <= threshold && matrix[i*cols+j] == 0 )
25         {
26             matrix[i*cols+j] = 1;
27             sum =1+ Count(threshold,matrix,rows,cols,i+1,j)+
28             Count(threshold,matrix,rows,cols,i,j+1)+
29             Count(threshold,matrix,rows,cols,i,j-1)+
30             Count(threshold,matrix,rows,cols,i-1,j);
31         }
32         return sum;
33     }
34 };

The idea at the beginning was wrong, thinking that starting from 0,0, there is only one way to go, how long is the longest?

The correct one is: what is the maximum range that can be reached? You can walk freely, so you can also use violence.

Code idea: just keep looking, mark the points you have passed

I've been looking for bugs for a long time, I want to kill myself when I find a bug, and the cols and rows are written backwards

Initialization can also be done with memset(matrix,0,sizeof(),matrix*rows*cols);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324897623&siteId=291194637