Skip to content

1102. Path With Maximum Minimum Value 👍

  • 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
35
36
37
38
39
40
41
struct T {
  int i;
  int j;
  int val;
  T(int i, int j, int val) : i(i), j(j), val(val) {}
};

class Solution {
 public:
  int maximumMinimumPath(vector<vector<int>>& grid) {
    constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    const int m = grid.size();
    const int n = grid[0].size();
    int ans = grid[0][0];
    vector<vector<bool>> seen(m, vector<bool>(n));
    auto compare = [](const T& a, const T& b) { return a.val < b.val; };
    priority_queue<T, vector<T>, decltype(compare)> maxHeap(compare);

    maxHeap.emplace(0, 0, grid[0][0]);

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

    throw;
  }
};
 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
44
class T {
  public int i;
  public int j;
  public int val;
  public T(int i, int j, int val) {
    this.i = i;
    this.j = j;
    this.val = val;
  }
}

class Solution {
  public int maximumMinimumPath(int[][] grid) {
    final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    final int m = grid.length;
    final int n = grid[0].length;
    int ans = grid[0][0];
    boolean[][] seen = new boolean[m][n];
    Queue<T> maxHeap = new PriorityQueue<>((a, b) -> b.val - a.val);

    maxHeap.offer(new T(0, 0, grid[0][0]));

    while (!maxHeap.isEmpty()) {
      final int i = maxHeap.peek().i;
      final int j = maxHeap.peek().j;
      final int val = maxHeap.poll().val;
      ans = Math.min(ans, val);
      if (i == m - 1 && j == n - 1)
        return ans;
      seen[i][j] = true;
      for (int[] dir : dirs) {
        final int x = i + dir[0];
        final int y = j + dir[1];
        if (x < 0 || x == m || y < 0 || y == n)
          continue;
        if (seen[x][y])
          continue;
        maxHeap.offer(new T(x, y, grid[x][y]));
      }
    }

    throw new IllegalArgumentException();
  }
}