题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路分析
这题和前面一道题一样,回溯法/感染。用一个数组标记有没有走过此位置,用全局变量count作为计数,用一个函数计算行和列坐标的数位和。终止条件为:下标越界;走过此位置;数位和大于阈值。
代码实现
public int count = 0;
public int movingCount(int threshold, int rows, int cols) {
if (rows == 0 || cols == 0) {
return -1;
}
int[][] matrix = new int[rows][cols];
process(threshold, rows, cols, 0, 0, matrix);
return count;
}
public void process(int threshold, int rows, int cols, int row, int col, int[][] matrix) {
int bitSum = countBit(row, col);
if (row < 0 || col < 0 || row >= rows || col >= cols || bitSum > threshold || matrix[row][col] == 1) {
return;
}
count++;
matrix[row][col] = 1;
process(threshold, rows, cols, row - 1, col, matrix);
process(threshold, rows, cols, row + 1, col, matrix);
process(threshold, rows, cols, row, col - 1, matrix);
process(threshold, rows, cols, row, col + 1, matrix);
}
public int countBit(int row, int col) {
int sum = 0;
while (row != 0) {
sum += row % 10;
row = row / 10;
}
while (col != 0) {
sum += col % 10;
col = col / 10;
}
return sum;
}