0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Leetcode 1926. Nearest Exit from Entrance in Maze

Posted at

1926. Nearest Exit from Entrance in Maze

アプローチ

BFS

class Solution {
    public int[] dx = {1, 0, -1, 0};
    public int[] dy = {0, 1, 0, -1};
    public int height;
    public int width;
    public boolean[][] isVisited;
    public Queue<Point1926> q;
    public int result = Integer.MAX_VALUE;

    public int nearestExit(char[][] maze, int[] entrance) {

        height = maze.length;
        width = maze[0].length;
        isVisited = new boolean[height][width];

        q = new LinkedList<>();

        q.add(new Point1926(entrance[0], entrance[1], 0));
        isVisited[entrance[0]][entrance[1]] = true;


        while (!q.isEmpty()) {
            Point1926 now = q.poll();

            for (int i = 0; i < 4; i++) {
                int nextX = dx[i] + now.x;
                int nextY = dy[i] + now.y;

                if (nextX < 0 || height <= nextX || nextY < 0 || width <= nextY) {
                    if (now.count == 0) {
                        continue;
                    }
                    result = Math.min(now.count, result);
                    continue;
                }

                if (isVisited[nextX][nextY] == true) {
                    continue;
                }

                if (maze[nextX][nextY] == '+') {
                    continue;
                }

                q.add(new Point1926(nextX, nextY, now.count + 1));
                isVisited[nextX][nextY] = true;


            }
        }
        return result == Integer.MAX_VALUE ? -1 : result;

    }
}

class Point1926 {
    int x;
    int y;
    int count;

    Point1926(int x, int y, int count) {
        this.x = x;
        this.y = y;
        this.count = count;
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?