LeetCode 684. Redundant Connection [Medium]

原題地址

題目內容

這裏寫圖片描述

題目分析

題目的意思大致爲,給了一個無向圖,讓我們刪掉組成環的最後一條邊。一開始想的做法是想採用拓撲排序來判斷是否由環,如果有再刪去多餘的邊。後面看了leetcode的discuss,發現他用了一個較爲簡單的方法,union find。建立一個長數組,來存儲每個節點,初始化爲-1,每加入一條新的邊(u,v),都通過find()函數來查找u之前是否有一條到V的路,如果有,那麼這條邊就是多餘的,如果沒有就添加到root數組裏面,root[u] = v,就代表有一條u->v的路徑。

代碼實現

class Solution {
public:
    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        vector<int> root(20001,-1);
        for(auto i:edges){
            int a = find(root,i[0]);
            int b = find(root,i[1]);
            if(a == b){
                return i;
            }
            else{
                root[a] = b;
            }
        }

    }
    int find(vector<int>&root,int x){
        while(root[x] != -1){
            x = root[x];
        }
        return x;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章