美文网首页
迷宫最短路径

迷宫最短路径

作者: packet | 来源:发表于2019-04-09 16:18 被阅读0次

    一道经典的迷宫题,在一个 m * n 的图中,找出某两个点的最短路径。

    public class Path {
    
        private int[][] maze;
        private int[][] offset;
    
        public Path(int m, int n) {
            this.maze = new int[m][n];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++)
                    maze[i][j] = ThreadLocalRandom.current().nextInt(2); // 0表示障碍
                System.out.println(Arrays.toString(maze[i]));
            }
    
            this.offset = new int[][] {
                    {-1, 0},
                    {1, 0},
                    {0, -1},
                    {0, 1}
            };
    
        }
    
        public void bfs(int x, int y) {
            if (maze[x][y] == 0) {
                throw new RuntimeException("no access");
            }
            int m = maze.length;
            int n = maze[0].length;
            Deque<Integer> queue = new LinkedList<>();
            int[][] distinct = new int[m][n];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++)
                    distinct[i][j] = -1;
            }
            distinct[x][y] = 0;
            int[][] vis = new int[m][n];
            queue.addLast(x * n + y);
            vis[x][y] = 1;
            Integer element;
            while ((element = queue.poll()) != null) {
                int p = element / n;
                int q = element % n;
                for (int i = 0; i < 4; i++) {
                    int a = p + offset[i][0];
                    int b = q + offset[i][1];
                    if (a >= 0 && a < m && b >= 0 && b < n && maze[a][b] == 1 && vis[a][b] == 0) {
                        vis[a][b] = 1;
                        distinct[a][b] = distinct[p][q] + 1;
                        queue.addLast(a * n + b);
                    }
                }
            }
    
            System.out.println("-----------------------------");
            for (int[] ints : distinct) {
                System.out.println(Arrays.toString(ints));
            }
            System.out.println("-----------------------------");
    
        }
    
        public static void main(String[] args) {
            Path path = new Path(8, 7);
            Scanner scanner = new Scanner(System.in);
    
            while (scanner.hasNextInt()) {
                int x = scanner.nextInt();
                int y = scanner.nextInt();
                path.bfs(x, y);
            }
    
        }
    }
    
    1. 采用的是BFS算法,需要一个队列,队列里的元素是整数,注意怎么和二维数组的坐标对应起来。
    2. 注意起点坐标x, y是怎么输入的

    相关文章

      网友评论

          本文标题:迷宫最短路径

          本文链接:https://www.haomeiwen.com/subject/nxhiiqtx.html