版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37770023/article/details/82904510
机器人运动范围(剑指offer)_学习记录
【题目描述】
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。
例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
【算法实现】
思路: 利用回溯法进行枚举可走路径;
/**
* 机器人的运动范围
* @author Guozhu Zhu
* @date 2018/9/30
* @version 1.0
*
*/
public class Solution {
public int movingCount(int threshold, int rows, int cols) {
//1. 参数校验
if (threshold <= 0 || rows <= 0 || cols <= 0) {
return 0;
}
//2. 标记
boolean[][] visitFlag = new boolean[rows][cols];
//3. 开始行走
return movingCore(0, 0, visitFlag, threshold);
}
public int movingCore(int i, int j, boolean[][] visitFlag, int threshold) {
if (i < 0 || j < 0 || i >= visitFlag.length || j >= visitFlag[0].length || visitFlag[i][j] == true || threshold < numSum(i)+numSum(j)) {
return 0;
}
visitFlag[i][j] = true;
return 1 + movingCore(i+1, j, visitFlag, threshold) +
movingCore(i-1, j, visitFlag, threshold) +
movingCore(i, j+1, visitFlag, threshold) +
movingCore(i, j-1, visitFlag, threshold);
}
public int numSum(int n) {
int sum = 0;
while (n > 0) {
sum += n%10;
n = n / 10;
}
return sum;
}
}