Series 55 wins the offer: range of motion of the robot

This topic ideas to keep up with a very similar, or backtracking. Is determined from the first block starts is greater than the limit value, then it is determined approximately vertical. This problem can be clearly seen judged should be the upper left area, so 0 is also very suitable as a starting point.

Backtracking seems like to use recursion, do pay attention to handling problems when the boundary values.

 1 class Solution {
 2 public:
 3     int movingCount(int threshold, int rows, int cols)
 4     {
 5         if (threshold < 0 || rows <= 0 || cols <= 0)
 6             return 0;
 7         bool *visited = new bool[rows*cols];
 8         memset(visited, 0, rows*cols);
 9         int count = getcount(threshold, rows, cols, 0, 0, visited);
10         delete[]visited;
11         return count;
12     }
13     int getcount(int threshold, int rows, int cols, int row, int col, bool *visit)//主函数
14     {
15         int count = 0;
16         if (row>=0&&row < rows&&col>=0&&col < cols && !visit[row*cols + col] && digitsum(threshold, row, col))
17         {
18             count++;
19             visit[row*cols + col] = true;
20             count += getcount(threshold, rows, cols, row, col + 1, visit)
21                 + getcount(threshold, rows, cols, row + 1, col, visit)
22                 + getcount(threshold, rows, cols, row - 1, col, visit)
23                 + getcount(threshold, rows, cols, row, col - 1, visit);
24         }
25         return count;
26 
27     }
28     bool digitsum(int threshold, int row, int col)
29     {
30         if (digitcomp(threshold, row)+digitcomp(threshold, col)<=threshold)
31             return true;
32         return false;
33     }
34     int digitcomp(int threshold, int n)
35     {
36         int sum=0;
37         while (n)
38         {
39             sum += n % 10;
40             n /= 10;
41         }
42         return sum;
43     }
44 };

This question is the last question to prove safety of the offer. I wrote this blog series is also coming to an end. Most of my questions written down, and no small part of the title is because I started to write on the github. Care about a practice to write code to hands every day. Next month is expected to brush a second time, will write something about algorithms and design patterns. I would like to be able to find a job ヾ favorite (◍ ° ∇ ° ◍) Techno ゙

Guess you like

Origin www.cnblogs.com/neverland0718/p/11274937.html