1102. Path With Maximum Minimum Value
Given a matrix of integers A
with R rows and C columns, find the maximum score of a path starting at [0,0]
and ending at [R-1,C-1]
.
The score of a path is the minimum value in that path. For example, the value of the path 8 → 4 → 5 → 9 is 4.
A path moves some number of times from one visited cell to any neighbouring unvisited cell in one of the 4 cardinal directions (north, east, west, south).
Example 1:
Input: [[5,4,5],[1,2,6],[7,4,6]]
Output: 4
Explanation:
The path with the maximum score is highlighted in yellow.
Example 2:
Input: [[2,2,1,2,2,2],[1,2,2,2,1,2]] Output: 2
Example 3:
Input: [[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]] Output: 3
1 class Solution { 2 public int maximumMinimumPath(int[][] A) { 3 int[][] DIRS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; 4 int n = A.length, m = A[0].length; 5 Queue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(b[0], a[0])); 6 pq.offer(new int[] { A[0][0], 0, 0 }); 7 int maxscore = A[0][0]; 8 A[0][0] = -1; // visited 9 while (!pq.isEmpty()) { 10 int[] top = pq.poll(); 11 maxscore = Math.min(maxscore, top[0]); 12 if (top[1] == n - 1 && top[2] == m - 1) 13 break; 14 for (int[] d : DIRS) { 15 int newi = d[0] + top[1], newj = d[1] + top[2]; 16 if (newi >= 0 && newi < n && newj >= 0 && newj < m && A[newi][newj] >= 0) { 17 pq.offer(new int[] { A[newi][newj], newi, newj }); 18 A[newi][newj] = -1; 19 } 20 } 21 } 22 return maxscore; 23 } 24 }