题解 | #机器人的运动范围#
机器人的运动范围
https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8
import java.util.*;
public class Solution {
int [][] dir={{-1,0},{1,0},{0,-1},{0,1}};
int res=0;
int cal(int n){
int sum=0;
while(n!=0){
sum+=(n%10);
n/=10;
}
return sum;
}
public int movingCount(int threshold, int rows, int cols) {
if(threshold<=0) return 1;
boolean[][] vis=new boolean[rows][cols];
int res=0;
Queue<ArrayList<Integer> >q=new LinkedList<ArrayList<Integer>>();
q.offer(new ArrayList<Integer>(Arrays.asList(0,0)));
vis[0][0]=true;
while(!q.isEmpty()){
ArrayList<Integer> node=q.poll();
res+=1;
for(int i=0;i<4;i++){
int x=node.get(0)+dir[i][0];
int y=node.get(1)+dir[i][1];
if(x >= 0 && x < rows && y >= 0 && y < cols && vis[x][y] != true){
if(cal(x) + cal(y) <= threshold){
q.offer(new ArrayList<Integer>(Arrays.asList(x, y)));
vis[x][y] = true;
}
}
}
}
return res;
}
}
//定义一个队列
Queue<ArrayList<Integer> >q=new LinkedList<ArrayList<Integer>>();
//开头元素加入队列
q.offer(new ArrayList<Integer>(Arrays.asList(0,0)));
//当队列不空时,进行循环,
while(!q.isEmpty()){
//弹出队列头元素
ArrayList<Integer> node=q.poll();
res+=1;
for(int i=0;i<4;i++){
int x=node.get(0)+dir[i][0];
int y=node.get(1)+dir[i][1];
if(x >= 0 && x < rows && y >= 0 && y < cols && vis[x][y] != true){
if(cal(x) + cal(y) <= threshold){
q.offer(new ArrayList<Integer>(Arrays.asList(x, y)));
vis[x][y] = true;
}
}
}
}
return res;
#bfs#