1102. 得分最高的路徑


描述

給你一個 R 行 C 列的整數矩陣 A。矩陣上的路徑從 [0,0] 開始,在 [R-1,C-1] 結束。
路徑沿四個基本方向(上、下、左、右)展開,從一個已訪問單元格移動到任一相鄰的未訪問單元格。
路徑的得分是該路徑上的 最小 值。例如,路徑 8 → 4 → 5 → 9 的值為 4 。
找出所有路徑中得分 最高 的那條路徑,返回其 得分。

思路

使用並查集+排序的方法,先對路徑節點從大到小進行排序,然后構造並查集,當起始點和終點連通時停止,連通圖中最小節點的值即是得分最高的路徑。

class Solution {
private:
    vector<int> root;

    typedef struct {
        int value;
        pair<int, int> index;
    } matrix;

    static bool cmp(const matrix &m, const matrix &n) {
        return m.value > n.value;
    }

public:
    int findRoot(int x) 
    {
        if (root[x] == x)
            return x;
        return findRoot(root[x]);
    }

    void unionRoot(int x, int y)
    {
        int a = findRoot(x);
        int b = findRoot(y);
        if (a != b) {
            root[a] = b;
        }
    }

    int maximumMinimumPath(vector<vector<int>>& A) {
        int M = A.size();
        if (M == 0)
            return 0;
        int N = A[0].size();
        if (N == 0)
            return 0;

        root = vector<int>(M*N, 0);
        for(int i=0; i<M*N; i++) {
            root[i] = i;
        }

        matrix record;
        vector<matrix> records;
        for (int i = 0; i < M; i++){
            for (int j = 0; j < N; j++) {
                record.value = A[i][j];
                record.index = make_pair(i, j);
                records.push_back(record);
            }
        }
        sort(records.begin(), records.end(), cmp);

        int minValue = min(A[0][0], A[M-1][N-1]);

        vector<vector<int>> tag(M, vector<int>(N, 0));
        tag[0][0] = 1;
        tag[M-1][N-1] = 1;

        int bId = 0;
        int eId = M * N - 1;
        vector<vector<int>> dirs ={{0,1}, {0,-1}, {-1,0}, {1, 0}};
        
        for (matrix record : records) {
            int x = record.index.first;
            int y = record.index.second;
            int rootIndex = x * N + y;
            tag[x][y] = 1;
            minValue = min(minValue, record.value);

            for (vector<int> id : dirs) {
                int nx = x + id[0];
                int ny = y + id[1];
                if (nx >= 0 && nx < M && ny >= 0 && ny < N && tag[nx][ny] == 1) {
                    int rootNIndex = nx * N + ny;
                    unionRoot(rootIndex, rootNIndex);
                }
            }

            if (findRoot(bId) == findRoot(eId)) {
                break;
            }
        }

        return minValue;
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM