Skip to content

778. Swim in Rising Water 👍

  • Time: $O(mn\log mn)$
  • Space: $O(mn)$
 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
class Solution {
 public:
  int swimInWater(vector<vector<int>>& grid) {
    constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    const int n = grid.size();
    int ans = grid[0][0];
    using T = tuple<int, int, int>;  // (grid[i][j], i, j)
    priority_queue<T, vector<T>, greater<>> minHeap;
    vector<vector<bool>> seen(n, vector<bool>(n));

    minHeap.emplace(grid[0][0], 0, 0);
    seen[0][0] = true;

    while (!minHeap.empty()) {
      const auto [height, i, j] = minHeap.top();
      minHeap.pop();
      ans = max(ans, height);
      if (i == n - 1 && j == n - 1)
        break;
      for (const auto& [dx, dy] : dirs) {
        const int x = i + dx;
        const int y = j + dy;
        if (x < 0 || x == n || y < 0 || y == n)
          continue;
        if (seen[x][y])
          continue;
        minHeap.emplace(grid[x][y], x, y);
        seen[x][y] = true;
      }
    }

    return ans;
  }
};
 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
class Solution {
  public int swimInWater(int[][] grid) {
    final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    final int n = grid.length;
    int ans = grid[0][0];
    Queue<int[]> minHeap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0])) {
      { offer(new int[] {grid[0][0], 0, 0}); } // (grid[i][j], i, j)
    };
    boolean[][] seen = new boolean[n][n];
    seen[0][0] = true;

    while (!minHeap.isEmpty()) {
      final int height = minHeap.peek()[0];
      final int i = minHeap.peek()[1];
      final int j = minHeap.poll()[2];
      ans = Math.max(ans, height);
      if (i == n - 1 && j == n - 1)
        break;
      for (int[] dir : dirs) {
        final int x = i + dir[0];
        final int y = j + dir[1];
        if (x < 0 || x == n || y < 0 || y == n)
          continue;
        if (seen[x][y])
          continue;
        minHeap.offer(new int[] {grid[x][y], x, y});
        seen[x][y] = true;
      }
    }

    return ans;
  }
}