【LeetCode(Java) - 490】迷宫

1、题目描述

在这里插入图片描述

2、解题思路

  本题是很经典的 BFS,特色在于往上下左右四个方向走的时候,不是走到邻居一个格子,而是一直往前,走到不能走为止。
  详情看代码。

3、解题代码

public class Solution {
    
    
    private int[][] directions = {
    
    {
    
    1, 0}, {
    
    -1, 0}, {
    
    0, -1}, {
    
    0, 1}};

    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
    
    
        int rows = maze.length;
        if (rows == 0) return false;
        int cols = maze[0].length;
        if (cols == 0) return false;
        return bfs(maze, start, destination, rows, cols);
    }

    private boolean bfs(int[][] maze, int[] start, int[] destination, int rows, int cols) {
    
    
        boolean[][] visited = new boolean[rows][cols];
        Queue<int[]> queue = new LinkedList<>();
        queue.add(start);
        visited[start[0]][start[1]] = true;
        while (!queue.isEmpty()) {
    
    
            int[] curPoint = queue.poll();  // 获取当前坐标
            int x = curPoint[0];
            int y = curPoint[1];
            if (x == destination[0] && y == destination[1]) {
    
    
                return true;
            }
            for (int[] direction : directions) {
    
    
                int newX = x + direction[0];
                int newY = y + direction[1];
                while (newX >= 0 && newX < rows && newY >= 0 && newY < cols && maze[newX][newY] == 0) {
    
    
                    // 只要是空格,就一路往前走,直到碰到墙壁
                    newX += direction[0];
                    newY += direction[1];
                }
                // 结束 while 时,说明当前点是墙壁或者超出边界,往回走一格
                newX -= direction[0];
                newY -= direction[1];
                // 如果这个停止点是曾经访问过的,则忽略
                if (!visited[newX][newY]) {
    
    
                    queue.add(new int[]{
    
    newX, newY});
                    visited[newX][newY] = true;
                }
            }
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_29051413/article/details/108529170