题解 | #机器人的运动范围#

机器人的运动范围

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#
全部评论

相关推荐

02-05 08:18
四川大学 Java
在思考的熊熊很讨厌吃香菜:不是,我门头沟学院呢?这都没排上?
点赞 评论 收藏
分享
想要offer的牛油果很大方:老哥,你啥时候面的,有timeline吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务