机器人的运动范围
约 450 字大约 2 分钟
题目:
地上有一个m行n列的方格。一个机器人从坐标 (0,0) 的格子开始移动,它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 (35,37) ,因为 3+5+3+7 = 18。但它不能进入方格 (35,38),因为3+5+3+8 = 19,请问该机器人能够到达多少个格子?
分析:
本题可以使用 回溯法,当它能够进入 (i, j) 格子的时候,再判断它能否进入 (i-1, j)、 (i+1, j)、 (i, j-1)、 (i, j+1) 这四个相邻的格子。
代码:
public class RobotMoveRange {
/**
* @param threshold 界限值
* @param rows 行数
* @param cols 列数
* @return
*/
public static int moveRange(int threshold, int rows, int cols) {
if (threshold < 0 || rows <= 0 || cols <= 0) {
return 0;
}
// 声明一个数组用来存储已计算的位置
boolean[] flag = new boolean[rows * cols];
return moveCount(threshold, rows, cols, 0, 0, flag);
}
/**
* @param threshold 界限值
* @param rows 行数
* @param cols 列数
* @param row 当前行
* @param col 当前列
* @param flag 是否已计算,防止重复
* @return
*/
private static int moveCount(int threshold, int rows, int cols, int row, int col, boolean[] flag) {
int count = 0;
while (row >= 0 && row < rows && col >= 0 && col < cols && getSum(row, col) <= threshold && !flag[row * cols + col]) {
flag[row * cols + col] = true;
// 向上、下、左、右四个方向计算
count = 1 + moveCount(threshold, rows, cols, row - 1, col, flag)
+ moveCount(threshold, rows, cols, row + 1, col, flag)
+ moveCount(threshold, rows, cols, row, col - 1, flag)
+ moveCount(threshold, rows, cols, row, col + 1, flag);
}
return count;
}
/**
* 计算当前位置数位和
*
* @param row 当前行
* @param col 当前列
* @return
*/
private static int getSum(int row, int col) {
return row / 10 + row % 10 + col / 10 + col % 10;
}
}