首页 > 其他 > 详细

【剑指offer】机器人的运动范围

时间:2020-03-06 23:16:34      阅读:60      评论:0      收藏:0      [点我收藏+]

题目链接:机器人的运动范围

 

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

 

题解:这题我最先开始是在快手的试题上做的。也是一个比较标准的回溯。把数字拆分一下,做判断,也是进行上下左右的递归即可。记得标记数组初始化!!!!!要不是gg给我找出来,我大概卡死//

 

代码:

 1 class Solution {
 2 public:
 3     int check(int num){
 4         int ans = 0;
 5         while(num){
 6             ans += num%10;
 7             num/=10;
 8         }
 9         return ans;
10     }
11     int countStep(int threshold,int rows,int cols,int row,int col,int visit[][105] ){
12         if(row < 0|| col < 0 || row >= rows || col >= cols || visit[row][col] == 1
13            || check(row)+check(col) > threshold) {
14             return 0;
15         }
16         visit[row][col] = 1;
17         return 1
18             + countStep(threshold,rows,cols,row+1,col,visit)
19             + countStep(threshold,rows,cols,row-1,col,visit)
20             + countStep(threshold,rows,cols,row,col+1,visit)
21             + countStep(threshold,rows,cols,row,col-1,visit);
22     }
23 
24     int movingCount(int threshold, int rows, int cols){
25         int visit[105][105];
26         memset(visit,0,sizeof(visit));//超级重要!!!!!!!
27         int ans = countStep(threshold,rows,cols,0,0,visit);
28         return ans;
29     }
30 };

 

【剑指offer】机器人的运动范围

原文:https://www.cnblogs.com/Asumi/p/12431137.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!