1 Title Description
2 ideas and methods
Step 1: Create a behavior rows, cols as an array of bool type, used to mark the location walked, initialized to false, true representation through .
Step two: function sum (int row, int col) for calculating bit i, j-th bit of the digital sum.
The third step: inspection查能否进入坐标为(row, col)的方格
Step Four: getSum(row,col) <= threshold && !visited[row*cols+col]表示可以走。
Fifth step: a fourth judgment step satisfy, this flag is true grid in the flag, flag gone through.
Step Six: recursion on this position, down, left, right, return recursively, down, left, right, plus 1 (add your own) and.
Step Seven: movingCount function call movingCountCore
function, i.e., the initial position of i = 0, j = 0, let the result of the recursive returned directly.
3 C ++ core code
1 class Solution { 2 public: 3 int movingCount(int threshold, int rows, int cols) 4 { 5 if(threshold <= 0|| rows <1 || cols<1) 6 return 0; 7 8 bool *visited = new bool[rows * cols]; 9 memset(visited,0,rows * cols); 10 11 intCOUNT = movingCountCore (threshold, rows, cols, 0 , 0 , visited); 12 is 13 is Delete [] visited; 14 15 return COUNT; 16 } . 17 18 is int movingCountCore ( int threshold, int rows, int cols, int Row, int COL , BOOL * visited) . 19 { 20 is int COUNT = 0 ; 21 is // check can enter the coordinates (row, col) of the box 22 is IF (Row> = 0 && row < rows && col>=0 && col<cols && getSum(row,col) <= threshold && !visited[row*cols+col]) 23 { 24 visited[row*cols + col] = true; 25 count = 1 + movingCountCore(threshold,rows,cols,row-1,col,visited) 26 + movingCountCore(threshold,rows,cols,row+1,col,visited) 27 + movingCountCore(threshold,rows,cols,row,col-1,visited) 28 + movingCountCore(threshold,rows,cols,row,col+1,visited); 29 } 30 return count; 31 } 32 33 // 得到数位和 34 int getSum(int row, int col) 35 { 36 int sum = 0; 37 while(row>0){ 38 sum += row%10; 39 row /= 10; 40 } 41 while(col>0){ 42 sum += col%10; 43 col /= 10; 44 } 45 return sum; 46 } 47 };
Reference material
https://blog.csdn.net/zjwreal/article/details/89296096,https://blog.csdn.net/u012477435/article/details/83351659#_1782
https://blog.csdn.net/qq_43109561/article/details/89670163
https://blog.csdn.net/Mr_XiaoZ/article/details/81174055?utm_source=blogxgwz1