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.

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

思路:用priorityqueue,dijkstra 算法,每次都是用最大的value去approach一個點,有點類似於 Trapping Rain WaterII 那題,每次都是用最大的value去算neighbor。T: O(mn*lg(mn)); 注意,dijkstra的算法,visited一定要在外面,而不是if block裏面進行判斷,否則會漏掉最優解;

class Solution {
    private class Node {
        public int x;
        public int y;
        public int minmax;
        public Node(int x, int y, int minmax) {
            this.x = x;
            this.y = y;
            this.minmax = minmax;
        }
    }
    
    private class NodeComparator implements Comparator<Node> {
        @Override
        public int compare(Node a, Node b) {
            return b.minmax - a.minmax;
        }
    }
    
    public int maximumMinimumPath(int[][] A) {
        int n = A.length;
        int m = A[0].length;
        int[][] dp = new int[n][m];
        
        boolean[][] visited = new boolean[n][m];
        PriorityQueue<Node> pq = new PriorityQueue<Node>(new NodeComparator());
        Node node = new Node(0, 0, A[0][0]);
        pq.offer(node);
        visited[0][0] = true;
        
        int[] dx = {0,0,-1,1};
        int[] dy = {-1,1,0,0};
        
        while(!pq.isEmpty()) {
            node = pq.poll();
            if(node.x == n - 1 && node.y == m - 1) {
                return node.minmax;
            }
            visited[node.x][node.y] = true;
            for(int k = 0; k < 4; k++) {
                int nx = node.x + dx[k];
                int ny = node.y + dy[k];
                if(0 <= nx && nx < n && 0 <= ny && ny < m && !visited[nx][ny]) {
                    Node newnode = new Node(nx, ny, 
                                            Math.min(node.minmax, A[nx][ny]));
                    pq.offer(newnode);
                }
            }
        }
        return -1;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章