回溯之机器人的运动范围
来源:互联网 发布:java金额大写转换 编辑:程序博客网 时间:2024/05/18 12:02
题目
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路
递归,判断每一次递归
1.不能越界
2.没走过
3.符合条件
public class Solution { public int movingCount(int threshold, int rows, int cols) { int[][] flag = new int[rows][cols]; return countHelper(flag, 0, 0, rows, cols, threshold); } public int countHelper(int[][] flag, int i, int j, int rows, int cols, int threshold){ if(i<0||i>=rows||j<0||j>=cols||flag[i][j]==1||!sum(i,j,threshold)) return 0; flag[i][j] = 1; return countHelper(flag, i-1, j, rows, cols, threshold) +countHelper(flag, i+1, j, rows, cols, threshold) +countHelper(flag, i, j-1, rows, cols, threshold) +countHelper(flag, i, j+1, rows, cols, threshold)+1; } public boolean sum(int x,int y, int threshold){ int m = 0; while(x!=0){ m += x%10; x = x/10; } while(y!=0){ m += y%10; y = y/10; } return m<=threshold; }}
阅读全文
0 0
- 回溯之机器人的运动范围
- 回溯法之机器人的运动范围
- 回溯法 机器人的运动范围
- 机器人运动范围--回溯算法
- 剑指offer 67题 【回溯法】机器人的运动范围
- 剑指offer——机器人的运动范围(回溯)
- 机器人的运动范围
- 机器人的运动范围
- 机器人的运动范围
- 机器人的运动范围
- 机器人的运动范围
- 机器人的运动范围
- 机器人的运动范围
- 机器人的运动范围
- 机器人的运动范围
- 机器人的运动范围
- 机器人的运动范围
- 机器人的运动范围
- ORACLE锁机制深入理解
- hdoj 6047( 2017 Multi-University Training Contest
- ROS动态参数设置dynamic_reconfigure出现“no rules to make”config文件时的方法
- 随机选择算法
- Spring 的核心机制:依赖注入(控制反转)
- 回溯之机器人的运动范围
- 2.class 和 public class的区别
- ES6(babel)环境搭建
- 九度1458:汉诺塔问题Ⅲ
- numpy中的axis=0,axis=1
- log4j 不同模块输出到不同的文件
- Ecilpse快捷键
- 安卓Notification和NotificationManager浅析
- PAT乙级1024. 科学计数法 (20)