和 剑指 Offer 12. 矩阵中的路径 是同一模板
java
class Solution {
int res = 0;
boolean[][] vis;
public int movingCount(int m, int n, int k) {
vis = new boolean[m][n];
dfs(0, 0, m, n, k);
return res;
}
void dfs(int x, int y, int m, int n, int k){
if(x < 0 || x >= m || y < 0 || y >= n || vis[x][y] || !check(x, y, k)) return;
res++;
vis[x][y] = true;
dfs(x + 1, y, m, n, k);
dfs(x - 1, y, m, n, k);
dfs(x, y + 1, m, n, k);
dfs(x, y - 1, m, n, k);
}
boolean check(int x, int y, int k){
return getNum(x) + getNum(y) <= k;
}
int getNum(int x){
int res = 0;
while(x != 0){
res += x % 10;
x /= 10;
}
return res;
}
}