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

机器人的运动范围

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

相关推荐

面了这么多场试,总有公司总喜欢压力面一个小时面试+手撕,哪里不会就点哪里,说了不会不会还继续追着问不尊重求职者,稍微有些细节记不清了,就开始怀疑项目真实性以及人格让求职者开摄像头但是自己不开,说话声音还贼小,pardon几次就开始不耐烦的不知道这个算不算,手撕的时候,面试官人跑了。。。最后快结束才来
一纸丿繁华丶:你换位思考一下,自己在职场被领导push麻了,身心俱疲,现在有个机会让你放松一下,体验一把上位者的感觉,还能看着那些高学历人才、未来自己的竞争者,抓耳挠腮、手足无措的样子,没给你当场笑出来就不错了,理解一下面试官吧。
点赞 评论 收藏
分享
昨天 16:58
华南理工大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务