思路:二维boolean记录走过的位置,每一步上下左右,四个方向走。
public class Solution {
public int movingCount(int threshold, int rows, int cols) {
boolean[][] bs = new boolean[rows][cols];
return f(bs, threshold, rows, cols, 0, 0);
}
int f(boolean[][] bs, int threshold, int rlen, int clen, int r, int c) {
int total = calc(r, c);
if (r < 0 || r >= rlen || c < 0 || c >= clen || bs[r][c] || total > threshold) return 0;
bs[r][c] = true;
return 1 +
f(bs, threshold, rlen, clen, r + 1, c) +
f(bs, threshold, rlen, clen, r - 1, c) +
f(bs, threshold, rlen, clen, r, c + 1) +
f(bs, threshold, rlen, clen, r, c - 1);
}
int calc(int a, int b) {
int res = 0;
while (a != 0) {
res += a % 10;
a /= 10;
}
while (b != 0) {
res += b % 10;
b /= 10;
}
return res;
}
}