思路:二维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;
}
}
该代码解决了一个问题,即在给定的二维网格中,从原点开始按照上、下、左、右四个方向移动,计算在每次移动后位置数字之和不超过阈值的最远距离。使用二维布尔数组记录已访问过的位置,通过递归函数f进行搜索并返回移动计数。
245

被折叠的 条评论
为什么被折叠?



