Skip to content

505. The Maze II 👍

  • Time: $O(mn \cdot \max(m, n))$
  • Space: $O(\max(m, n))$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
 public:
  int shortestDistance(vector<vector<int>>& maze, vector<int>& start,
                       vector<int>& destination) {
    constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    const int m = maze.size();
    const int n = maze[0].size();
    queue<pair<int, int>> q{{{start[0], start[1]}}};
    vector<vector<int>> dist(m, vector<int>(n, INT_MAX));
    dist[start[0]][start[1]] = 0;

    while (!q.empty()) {
      const auto [i, j] = q.front();
      q.pop();
      for (const auto& [dx, dy] : dirs) {
        int x = i;
        int y = j;
        int step = dist[i][j];
        while (isValid(maze, x + dx, y + dy)) {
          x += dx;
          y += dy;
          ++step;
        }
        if (step < dist[x][y]) {
          dist[x][y] = step;
          if (x == destination[0] && y == destination[1])
            continue;
          q.emplace(x, y);
        }
      }
    }

    return dist[destination[0]][destination[1]] == INT_MAX
               ? -1
               : dist[destination[0]][destination[1]];
  }

 private:
  bool isValid(const vector<vector<int>>& maze, int x, int y) {
    return x >= 0 && x < maze.size() && y >= 0 && y < maze[0].size() &&
           maze[x][y] == 0;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
  public int shortestDistance(int[][] maze, int[] start, int[] destination) {
    final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    final int m = maze.length;
    final int n = maze[0].length;
    Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(start[0], start[1])));
    int[][] dist = new int[maze.length][maze[0].length];
    Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));
    dist[start[0]][start[1]] = 0;

    while (!q.isEmpty()) {
      final int i = q.peek().getKey();
      final int j = q.poll().getValue();
      for (int[] dir : dirs) {
        int x = i;
        int y = j;
        int step = dist[i][j];
        while (isValid(maze, x + dir[0], y + dir[1])) {
          x += dir[0];
          y += dir[1];
          ++step;
        }
        if (step < dist[x][y]) {
          dist[x][y] = step;
          q.offer(new Pair<>(x, y));
        }
      }
    }

    return dist[destination[0]][destination[1]] == Integer.MAX_VALUE
        ? -1
        : dist[destination[0]][destination[1]];
  }

  private boolean isValid(int[][] maze, int x, int y) {
    return x >= 0 && x < maze.length && y >= 0 && y < maze[0].length && maze[x][y] == 0;
  }
}