LeetCode 1102. Path With Maximum Minimum Value

Problem Description:

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).

题解:

此题的解决思路是贪心,类似于dijkstra的方法。需要一个优先队列来存下能刚访问到的值最大的点作为候选,能够访问到的点是已经访问的点的四周的点(初始状态的时候能够访问的点是位于(0, 0)位置的点)。

代码如下:

int[][] dirs = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
    public int maximumMinimumPath(int[][] A) {
        int m = A.length, n = A[0].length;
        boolean[][] visited = new boolean[m][n];
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (b[0] - a[0]));
        pq.offer(new int[]{A[0][0], 0, 0});
        int res = A[0][0];
        visited[0][0] = true;
        
        while(!pq.isEmpty()) {
            int[] top = pq.poll();
            // System.out.println(top[0] + " " + top[1] + " " + top[2]);
            res = Math.min(res, top[0]);
            if(top[1] == m - 1 && top[2] == n - 1) {
                break;
            }
            for(int[] dir : dirs) {
                int x = dir[0] + top[1];
                int y = dir[1] + top[2];
                // System.out.println("can" + " " + x + " " + y);
                if(x < 0 || x >= m || y < 0 || y >= n || visited[x][y]) continue;
                // System.out.println("add" + A[x][y] + " " + x + " " + y);
                pq.offer(new int[]{A[x][y], x, y});
                visited[x][y] = true;
            }
        }
        return res;
    }

猜你喜欢

转载自www.cnblogs.com/rookielet/p/11146393.html