题解 | #机器人的运动范围#
机器人的运动范围
https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8
import java.util.*;
public class Solution {
int step = 0;
public int movingCount(int threshold, int rows, int cols) {
boolean[][] tag = new boolean[100][100];
checkMoving(threshold, rows, cols, 0, 0,tag);
return step;
}
public void checkMoving(int threshold, int rows, int cols, int rowIndex,
int colIndex,boolean[][] tag) {
if (rowIndex < 0 || colIndex < 0 || rowIndex >= rows || colIndex >= cols ||
tag[rowIndex][colIndex]
) {
return ;
}
tag[rowIndex][colIndex] = true;
if ((sumResult(rowIndex) + sumResult(colIndex) > threshold)) {
return;
}
step++;
checkMoving(threshold, rows, cols, rowIndex + 1, colIndex,tag);
checkMoving(threshold, rows, cols, rowIndex - 1, colIndex,tag);
checkMoving(threshold, rows, cols, rowIndex, colIndex + 1,tag);
checkMoving(threshold, rows, cols, rowIndex, colIndex - 1,tag);
}
private int sumResult(int num) {
int sum = 0;
do {
sum += (num % 10);
num = num / 10;
} while (num > 0);
return sum;
}
}
#动态规划#