经典BFS走迷宫问题

机器人的运动范围

http://www.nowcoder.com/questionTerminal/6e5207314b5241fb83f2329e89fdecc8

思想:通过队列实现BFS,尝试每一种路径可能。若当前位置可以走,则把当前位置标志已访问。

import java.util.*;
class Node{
    int x;
    int y;
    public Node(int x, int y){
        this.x = x;
        this.y = y;
    }
}
public class Solution {

    public int movingCount(int threshold, int rows, int cols)
    {
        //标志位,表示是否已走过
        int[][]visits = new int[rows][cols];
        //上下左右四个方向
        int[][]dir = {{-1,0}, {1,0}, {0,-1}, {0,1}};
        Queue<Node>queue = new LinkedList<Node>();
        queue.offer(new Node(0,0));
        visits[0][0] = 1;
        int count = 1;
        if(threshold<0)return 0;
        while(!queue.isEmpty()){
            Node node = queue.poll();
            for(int i=0; i<dir.length; i++){
                int x = node.x + dir[i][0];
                int y = node.y + dir[i][1];
                if(x>=0 && x<rows && y>=0 && y<cols){
                    //当前方向可以走并且x y位数之和小于threshold,入队
                    if(visits[x][y]==0 && check(x,y,threshold)){
                        queue.offer(new Node(x, y));
                        visits[x][y] = 1;
                        count++;
                    }
                }
            }
        }
        return count;
    }

    //判断x y是否位数之和是否小于等于threshold
    public static Boolean check(int x, int y, int threshold){
        int t1 = 0;
        while(x!=0){
            t1 += x%10;
            x/=10;
        }
        int t2 = 0;
        while(y!=0){
            t2 += y%10;
            y/=10;
        }
        if(t1+t2 <= threshold)
            return true;
        return false;
    }
}
全部评论

相关推荐

04-03 09:32
已编辑
华南农业大学 golang
我的代码出BUG了:"晚点发个邮件调整一下时间",你收到新的邮件没,如果没有收到新的邮件,那就需要进入面试链接留痕,否则系统会判定你迟到
点赞 评论 收藏
分享
03-29 18:59
运城学院 Java
程序员小白条:咱们要对自己的简历和学历有清晰的认知,不要动不动就大厂了....都26届了,没实习还想着大厂,唉
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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