题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
实现
public class Solution13 {
public static void main(String[] args) {
System.out.println(movingCount(5, 10, 10));
}
/**
* @param threshold 约束值
* @param rows 行数
* @param cols 列数
* @return
*/
public static int movingCount(int threshold, int rows, int cols) {
boolean[] visited = new boolean[rows * cols];
return move(threshold, rows, cols, 0, 0, visited);
}
/**
* 递归回溯
*
* @param threshold 约束值
* @param rows 方格行数
* @param cols 方格列数
* @param row 当前行
* @param column 当前列
* @param visited boolean数组,记录相应位置的元素是否被访问过
* @return
*/
public static int move(int threshold, int rows, int cols, int row, int column, boolean[] visited) {
int count = 0;
if (check(threshold, rows, cols, row, column, visited)) {
visited[row * cols + column] = true;
count = 1 + move(threshold, rows, cols, row - 1, column, visited)
+ move(threshold, rows, cols, row + 1, column, visited)
+ move(threshold, rows, cols, row, column - 1, visited)
+ move(threshold, rows, cols, row, column + 1, visited);
}
return count;
}
private static boolean check(int threshold, int rows, int cols, int row, int column, boolean[] visited) {
return row >= 0 && row < rows && column >= 0 && column < cols && !visited[row * cols + column] && (getDigitSum(row) + getDigitSum(column) <= threshold);
}
//计算数组下标数字之和
private static int getDigitSum(int number) {
int sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
}
网友评论