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

思路:破题思路,想最后一个点,上边和左边过来,每条路径的value是这条路径上的最小,但是我首先是跟上边和左边过来的最大值进行比较,所以pq是为了处理每次四个方向扩散,首先扩散最大的value,这题跟waterII很类似,water是每次过来取四周最小值,先进行扩散,这里相反,每次取最大值进行扩散,T: O(mn*lg(mn)); 注意,dijkstra的算法,visited一定要在外面,而不是if block里面进行判断,否则会漏掉最优解;

class Solution {
    public class Node {
        public int x;
        public int y;
        public int value;
        public Node(int x, int y, int value) {
            this.x = x;
            this.y = y;
            this.value = value;
        }
    }
    
    public int maximumMinimumPath(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) -> (b.value - a.value));
        pq.offer(new Node(0, 0, grid[0][0]));
        
        int[][] dirs = {{0,1},{0,-1},{-1,0},{1,0}};
        boolean[][] visited = new boolean[m][n];
        while(!pq.isEmpty()) {
            Node node = pq.poll();
            if(node.x == m - 1 && node.y == n - 1) {
                return node.value;
            }
            if(visited[node.x][node.y]) {
                continue;
            }
            visited[node.x][node.y] = true;
            for(int[] dir: dirs) {
                int nx = node.x + dir[0];
                int ny = node.y + dir[1];
                if(0 <= nx && nx < m && 0 <= ny && ny < n && !visited[nx][ny]) {
                    pq.offer(new Node(nx, ny, Math.min(grid[nx][ny], node.value)));
                }
            }
        }
        return -1;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值