思路:DFS或者BFS
DFS版本
class Solution {
public int movingCount(int m, int n, int k) {
boolean[][] visited = new boolean[m][n];
return dfs(m, n, k, visited, 0, 0);
}
public int dfs(int m, int n, int k, boolean[][] visited, int x, int y){
if(x < 0 || x >= m || y < 0 || y >= n || (digitsum(x) + digitsum(y) > k) || visited[x][y]){
return 0;
}
visited[x][y] = true;
int[] dx = {0,0,1,-1};
int[] dy = {1,-1,0,0};
// 第一次是[0,0]进来,所以count从1开始
int count = 1;
for(int i = 0; i < 4; i++){
int next_x = x + dx[i], next_y = y + dy[i];
count += dfs(m, n, k ,visited, next_x, next_y);
}
return count;
}
public int digitsum(int m){
int sum = 0;
while(m != 0){
sum += m % 10;
m /= 10;
}
return sum;
}
}
也可以这么写,这就不需要写方向数组了
return 1 + dfs(m, n, k, visited, x, y+1)
+ dfs(m, n, k, visited, x, y-1)
+ dfs(m, n, k, visited, x-1, y)
+ dfs(m, n, k, visited, x+1, y);
BFS版本
class Solution {
public int movingCount(int m, int n, int k) {
if(k == 0) return 1;
Queue<int[]> queue = new LinkedList<>();
int ans = 1;
boolean[][] visited = new boolean[m][n];
queue.offer(new int[]{0,0});
visited[0][0] = true;
while(!queue.isEmpty()){
int[] cell = queue.poll();
int x = cell[0], y = cell[1];
int[] dx = {0, 1};
int[] dy = {1, 0};
for (int i = 0; i < 2; i++) {
int next_x = x + dx[i], next_y = y + dy[i];
if (next_x < 0 || next_x >= m || next_y < 0 || next_y >= n || visited[next_x][next_y] || get(next_x) + get(next_y) > k){
continue;
}
queue.offer(new int[]{next_x, next_y});
// 标记为已访问
visited[next_x][next_y] = true;
ans += 1;
}
}
return ans;
}
int get(int x){
int sum = 0;
while (x != 0){
sum += x % 10;
x /= 10;
}
return sum;
}
}