剑指offer66:机器人的运动范围

1 题目描述

  地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

2 思路和方法

  回溯法:

  是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。

  第一步:创建一个行为rows,列为cols的bool型数组,用来标记走过的位置,初始化为false,true表示走过

  第二步:函数sum (int row, int col)用来计算第i位,第j位的数位之和。

  第三步:检查能否进入坐标为(row, col)的方格

  第四步:getSum(row,col) <= threshold && !visited[row*cols+col]表示可以走。

  第五步:满足第四步的判断,将此格子在flag中标记为true,标记走过了。

  第六步:递归这个位置的上、下、左、右,返回递归的上、下、左、右再加1(加上自己)的和。

  第七步:在movingCount函数中调用movingCountCore函数,初始的位置即i=0,j=0,让其递归出的结果直接返回。

3 C++核心代码    

 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         int count = movingCountCore(threshold,rows,cols,0,0,visited);
12         
13         delete[] visited;
14         
15         return count;
16     }
17     
18     int movingCountCore(int threshold,int rows, int cols, int row, int col, bool* visited)
19     {
20         int count = 0;
21         // 检查能否进入坐标为(row, col)的方格
22         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 };
View Code

参考资料

https://blog.csdn.net/zjwreal/article/details/89296096https://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

posted @ 2019-08-31 19:50  wxwreal  阅读(144)  评论(0编辑  收藏  举报