文章目录
面试题12:机器人的运动范围
一、题目描述
地上有一个m行n列的方格。一个机器人从坐标(0, 0)的格子开始移动,它每一次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格(35, 37),因为3+5+3+7=18。但它不能进入方格(35, 38),因为3+5+3+8=19。请问该机器人能够到达多少个格子?
二、问题分析
这道题与上一道面试题太相似了 面试题11:矩阵中的路径,我有点不太理解,剑指Offer这本书中为啥有两道这么相似的题。
看了看本题考点意思是:
- 矩阵中的路径这种问题 是告诉你
通常二维矩阵找路径这类问题可以应用回溯法来解决
。 - 机器人的运动范围 这种问题是告诉你
通常物体或人在二维方格运动问题可以应用回溯法来解决
。
算法思想基本上保持一致,直接公布解答吧。不懂的参考 面试题11:矩阵中的路径,这个说的已经非常详细了。
三、问题解答
/**
* @param threshold 规定限制的行坐标和列坐标的数位之和
* @param rows 行数
* @param cols 列数
* @return 格子的数量
*/
public int movingCount(int threshold, int rows, int cols) {
if (rows <= 0 || cols <= 0 || threshold < 0)
return 0;
// 记录状态 默认为false
boolean[] isVisited = new boolean[rows * cols];
Arrays.fill(isVisited, false);
int count = movingCountCore(threshold, rows, cols, 0, 0, isVisited);// 用两种方法试一下
return count;
}
// 解空间
private int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[] isVisited) {
// 剪枝
if (row < 0 || col < 0 || row >= rows || col >= cols || isVisited[row * cols + col]
|| cal(row) + cal(col) > threshold) {
return 0;
}
// 记录已访问
isVisited[row * cols + col] = true;
return 1 + movingCountCore(threshold, rows, cols, row - 1, col, isVisited)
+ movingCountCore(threshold, rows, cols, row + 1, col, isVisited)
+ movingCountCore(threshold, rows, cols, row, col - 1, isVisited)
+ movingCountCore(threshold, rows, cols, row, col + 1, isVisited);
}
private int cal(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}