题目
https://www.acwing.com/problem/content/description/22/
思路
bfs。yxc大佬说如果数据大的时候c++写dfs可能会爆栈。
Java代码
import java.util.LinkedList;
class Solution {
int[] dx = new int[]{-1, 0, 1, 0};
int[] dy = new int[]{0, 1, 0, -1};
public int movingCount(int threshold, int rows, int cols){
if(rows == 0 || cols == 0) return 0;
int res = 0;
boolean[][] st = new boolean[rows][cols];
LinkedList<int[]> q = new LinkedList<>();
q.add(new int[]{0, 0});
while(!q.isEmpty()){
int[] t = q.pop();
if(sum(t[0])+sum(t[1]) > threshold || st[t[0]][t[1]] == true)
continue;
res++;
st[t[0]][t[1]] = true;
for(int i=0; i<4; i++){
int x = rows+dx[i], y = rows+dy[i];
if(t[0] >= 0 && t[0] <rows && t[1] >=0 && t[1] < cols)
q.add(new int[]{t[0], t[1]});
}
}
return res;
}
private static int sum(int x){
int ret = 0;
while(x !=0 ){
ret += x%10;
x /= 10;
}
return ret;
}
}