华为机试题HJ43 迷宫问题

迷宫问题

http://www.nowcoder.com/questionTerminal/cf24906056f4488c9ddb132f317e03bc

//层次优先遍历的思想,每次找到最近的位置进行外扩,如果外扩到目标节点说明找到了最短路径

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] dx = new int[]{0, 0, 1, -1};
        int[] dy = new int[]{1, -1, 0, 0};
        while (in.hasNext()) {
            int n = in.nextInt(), m = in.nextInt();
            int[][] grid = new int[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    grid[i][j] = in.nextInt();
                }
            }
            String res = "";
            boolean[][] visit = new boolean[n][m];
            //优先级队列存储每个位置上的信息
            PriorityQueue<Cell> minHeap = new PriorityQueue<>();
            minHeap.add(new Cell(0, 0, 0, "(0,0)"));
            while(!minHeap.isEmpty()){
                //每次选最小距离的位置进行扩散访问
                Cell cell = minHeap.poll();
                //如果位置已经被访问过说明有更短的路径到此处,不用继续访问(剪枝)
                if(visit[cell.x][cell.y]){
                    continue;
                }
                visit[cell.x][cell.y] = true;
                //到达目标节点输出结果路径
                if(cell.x == n - 1 && cell.y == m - 1){
                    res = cell.path;
                    break;
                }
                for (int i = 0; i < 4; i++) {
                    int newX = cell.x + dx[i];
                    int newY = cell.y + dy[i];
                    //四个方向都走下,如果不是墙就记录下位置的到达信息
                    if(!isOverBound(newX, newY, n, m) && grid[newX][newY] == 0){
                        minHeap.add(new Cell(newX, newY, cell.dis + 1, cell.path + "\n(" + newX + "," + newY + ")"));
                    }
                }
            }
            System.out.println(res);
        }
    }

    public static boolean isOverBound(int x, int y, int n, int m){
        return x < 0 || y < 0 || x >= n || y >= m;
    }

    static class Cell implements Comparable<Cell>{
        int x;
        int y;
        //从初始位置到达此处的位置
        int dis;
        //从初始位置到达该位置的路径
        String path;

        public Cell(int x, int y, int dis, String path) {
            this.x = x;
            this.y = y;
            this.dis = dis;
            this.path = path;
        }

        //队列中元素按可达距离排序
        @Override
        public int compareTo(Cell o) {
            return this.dis - o.dis;
        }
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 17:13
想去,但是听说加班强度实在难崩,所以拒绝了,现在有点心梗对面hr感觉也是实习生,打电话的时候怪紧张的,但是感觉人很好嘞
水中水之下水道的鼠鼠:哥们这不先去体验一下,不行再跑呗,大不了混个实习经历(有更好的转正offer就当我没说)
点赞 评论 收藏
分享
屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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