方法一:dfs
visited[i][j]=true;没有再回溯是因为k的值是不变的,遍历后一旦不符合就是永远不符合要求,不用回溯。
public int movingCount(int m, int n, int k){
boolean[][] visited=new boolean[m][n];
return dfs(visited,m,n,k,0,0);
}
public int dfs(boolean[][] visited,int m,int n,int k,int i,int j){
if(i>=m||j>=n||visited[i][j]||bitSum(i)+bitSum(j)>k) return 0;
visited[i][j]=true;
return 1+dfs(visited,m,n,k,i+1,j)+dfs(visited,m,n,k,i,j+1);
}
public int bitSum(int n){
int sum=0;
while(n>0){
sum+=n%10;
n/=10;
}
return sum;
}
方法二:bfs
public int movingCount(int m, int n, int k){
boolean[][] visited=new boolean[m][n];
int res=0;
Queue<int[]> queue=new LinkedList<>();
queue.add(new int[]{0,0,0,0});
while(!queue.isEmpty()){
int[] array=queue.poll();
int i=array[0];
int j=array[1];
if(i>=m||j>=n||array[2]+array[3]>k||visited[i][j]) continue;
visited[i][j]=true;
res++;
queue.add(new int[]{i+1,j,bitSum(i+1),bitSum(j)});
queue.add(new int[]{i,j+1,bitSum(i),bitSum(j+1)});
}
return res;
}
public int bitSum(int n){
int sum=0;
while(n>0){
sum+=n%10;
n/=10;
}
return sum;
}