剑指offer-66题 机器人的运动范围
来源:互联网 发布:群组推荐算法 编辑:程序博客网 时间:2024/06/09 19:17
题目:
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路:
此题的思路和上一道题很像,都用到了DFS,因此可以使用递归来实现。当机器人运动到一个可行的点后需要将计数器的值加一,之后分别在左、右、上、下进行搜索。搜索到符合条件的点则计数器(rcount)的值加一,不符合条件则返回0.
解题代码:
public class Solution { /** * * @method Desc:计算出机器人走过的格子数 * @date 2017-10-28上午8:42:09 */ public int movingCount(int threshold, int rows, int cols){ if(rows == 0 || cols == 0) return 0; //构建访问矩阵 boolean [][]visited = new boolean [rows][cols]; for(int i=0;i<rows;i++){ Arrays.fill(visited[i], false); } //计算走过的方格的个数 return Availability(threshold, rows, cols, 0, 0, 0, visited); } //查找走过的路径 public int Availability(int threshold, int rows, int cols,int i,int j,int count,boolean [][]visited){ int rcount = count; if(i>=rows || i<0){ return rcount; } if(j>=cols || j<0){ return rcount; } if(visited[i][j]){ return rcount; } int x = i, y = j; //计算坐标和 int sum = 0; while(i != 0){ sum += i%10; i/= 10; } while(j != 0){ sum += j%10; j/= 10; } if(sum <= threshold){ visited[x][y] = true; rcount = 1 + Availability(threshold,rows,cols,x,y+1,rcount,visited) +Availability(threshold,rows,cols,x,y-1,rcount,visited) +Availability(threshold,rows,cols,x+1,y,rcount,visited) +Availability(threshold,rows,cols,x-1,y,rcount,visited); }else{ return rcount; } return rcount; }}
阅读全文
0 0
- 剑指offer 66 机器人的运动范围
- 剑指offer-66题 机器人的运动范围
- 剑指offer--机器人的运动范围
- 剑指offer 67-机器人的运动范围
- 《剑指offer》机器人的运动范围
- 剑指offer—机器人的运动范围
- [剑指offer]机器人的运动范围
- 《剑指offer》:[67]机器人的运动范围
- 剑指offer-机器人的运动范围
- 剑指offer-机器人的运动范围
- 剑指offer 机器人的运动范围
- 剑指Offer:机器人的运动范围
- 剑指offer-机器人的运动范围
- 剑指offer-----机器人的运动范围 java
- 剑指offer 机器人的运动范围
- 剑指Offer—66—机器人的运动范围
- 剑指offer 67题 【回溯法】机器人的运动范围
- 剑指offer | 训练题65:机器人的运动范围
- C 字符串
- 如何页面加载另外一个页面
- C语言实验——输入数字星期,输出英文(switch语句)
- java 字符串特性及常用实体类操作
- 小车制作过程中遇到的几个问题
- 剑指offer-66题 机器人的运动范围
- 基于STM32F429的IAP升级(HAL库/RS485)
- 17. Letter Combinations of a Phone Number
- java static专题
- React学习(四):使用组件构建应用程序
- java 集合类及其常用操作总结
- [noip2012]借教室
- github遇到的坑1
- Linux的uboot Makefile笔记