Leetcode Maze 总结

本文介绍了一种在迷宫中寻找从起点到终点路径的方法,包括判断可达性的BFS和DFS算法,以及寻找最短路径的BFS算法,并提供了一个寻找最短路径且记录路径方向的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling updownleft or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.

Given the ball's start position, the destination and the maze, determine whether the ball could stop at the destination.

The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.

Maze I  (BFS)

判断是否可以到达 目的地

    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
        int m = maze.length, n = maze[0].length;
        boolean[][] visited = new boolean[m][n];
        int[] dx = new int[] { 0, 0, 1, -1};
        int[] dy = new int[] {-1, 1, 0, 0};
        
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(start);
        visited[start[0]][start[1]] = true;
        
        while (!queue.isEmpty()) {
            int[] curr_pos = queue.poll();
            if (curr_pos[0] == destination[0] && curr_pos[1] == destination[1]) return true;
            
            for (int i = 0; i < 4; i++) {
                int x = curr_pos[0], y = curr_pos[1];
                while (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == 0) {
                    x += dx[i];
                    y += dy[i];
                }
                x -= dx[i];
                y -= dy[i];
                
                if (!visited[x][y]) {
                    visited[x][y] = true;
                    queue.offer(new int[] {x, y});
                }
            }
            
        }
        return false;

(DFS)

    int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
        if (maze == null || maze.length == 0 || maze[0].length == 0) return false;
        return dfs(maze, start, destination, new boolean[maze.length][maze[0].length]);
    }
    
    private boolean dfs(int[][] maze, int[] current, int[] des, boolean[][] visited) {
        if (current[0] == des[0] && current[1] == des[1]) return true;
        int x = current[0], y = current[1];
        int m = maze.length, n = maze[0].length;
        if (x < 0 || x > m || y < 0 || y > n || visited[x][y]) return false;
        visited[x][y] = true;
        for (int i = 0; i < dirs.length; i++) {
            int dx = x, dy = y;
            while (dx >= 0 && dx < m && dy >= 0 && dy < n && maze[dx][dy] == 0) {
                dx += dirs[i][0];
                dy += dirs[i][1];
            }
            int[] pos = new int[] {dx -= dirs[i][0], dy -= dirs[i][1]};
            if (dfs(maze, pos, des, visited)) return true;
        }
        return false;
    }


Maze II


Given the ball's start position, the destination and the maze, find the shortest distance for the ball to stop at the destination. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included). If the ball cannot stop at the destination, return -1.

找到 到达目的地的最短路线

(BFS)

public int shortestDistance(int[][] maze, int[] start, int[] destination) {
        Queue<int[]> q = new LinkedList<>();
        int m = maze.length, n = maze[0].length;
        int[][] dist = new int[m][n];
        for (int i = 0; i < m; i++) {
            Arrays.fill(dist[i], Integer.MAX_VALUE);
        }
        int[] dx = new int[] {-1, 0, 1, 0};
        int[] dy = new int[] { 0, 1, 0, -1};
        
        q.offer(start);
        dist[start[0]][start[1]] = 0;
        
        while (!q.isEmpty()) {
            int[] p = q.poll();
            for (int i = 0; i < 4; i++) {
                int x = p[0] + dx[i], y = p[1] + dy[i];
                int cnt = 1;
                
                while (x >=0 && x < m && y >= 0 && y < n && maze[x][y] != 1) {
                    x += dx[i];
                    y += dy[i];
                    cnt++;
                }
                x -= dx[i];
                y -= dy[i];
                cnt--;
                if (dist[p[0]][p[1]] + cnt < dist[x][y]) {
                    dist[x][y] = dist[p[0]][p[1]] + cnt;
                    q.offer(new int[] {x, y});
                }
            }
        }
        return dist[destination[0]][destination[1]] == Integer.MAX_VALUE ? -1 : dist[destination[0]][destination[1]];
    }


Maze III


public String findShortestWay(int[][] maze, int[] ball, int[] hole) {
        int m = maze.length;
        int n = maze[0].length;

        PriorityQueue<Point> pq = new PriorityQueue<Point>();
        Point start = new Point(ball[0], ball[1], 0, "");
        pq.offer(start);
        
        boolean[][] visited = new boolean[m][n];
        String[] directions = {"u", "r", "d", "l"};
        int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
        while(!pq.isEmpty()) {
            Point p = pq.poll();
            if(p.x == hole[0] && p.y == hole[1])
                return p.path;
                
            if(visited[p.x][p.y]) continue;
            visited[p.x][p.y] = true;

            for(int i = 0; i < dirs.length; i++) {
                int x = p.x;
                int y = p.y;
                int len = p.len;
                while(x + dirs[i][0] >= 0 && x + dirs[i][0] < m && y + dirs[i][1] >= 0 && y + dirs[i][1] < n && maze[x + dirs[i][0]][y + dirs[i][1]] != 1 && (x != hole[0] || y != hole[1])) {
                    x += dirs[i][0];
                    y += dirs[i][1];
                    len++;
                }
                
                Point next = new Point(x, y, len, p.path + directions[i]);
                pq.offer(next);
            }
            
        }
        return "impossible";
    }
    
    class Point implements Comparable<Point> {
        int x;
        int y;
        int len;
        String path;
        
        Point(int x, int y) {
            this.x = x;
            this.y = y;
            len = Integer.MAX_VALUE;
            path = "";
        }
        
        Point(int x, int y, int len, String path) {
            this.x = x;
            this.y = y;
            this.len = len;
            this.path = path;
        }
        
        public int compareTo(Point p) {
            return this.len == p.len? this.path.compareTo(p.path) : this.len - p.len;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值