431.找無(wú)向圖的連通塊

描述

找出無(wú)向圖中所有的連通塊乎完。
圖中的每個(gè)節(jié)點(diǎn)包含一個(gè)label屬性和一個(gè)鄰接點(diǎn)的列表。(一個(gè)無(wú)向圖的?連通塊是一個(gè)子圖品洛,其中任意兩個(gè)頂點(diǎn)通過(guò)路徑相連树姨,且不與整個(gè)圖中的其它頂點(diǎn)相連。)

注意事項(xiàng)

每個(gè)連通塊內(nèi)部應(yīng)該按照l(shuí)abel屬性排序

說(shuō)明

Learn more about representation of graphs

樣例

給定圖:

    A------B  C
     \     |  | 
      \    |  |
       \   |  |
        \  |  |
          D   E

返回 {A,B,D}, {C,E}桥状。其中有 2 個(gè)連通塊帽揪,即{A,B,D}, {C,E}

注意事項(xiàng)

每個(gè)連通塊內(nèi)部應(yīng)該按照l(shuí)abel屬性排序

思路

本題bfs的做法還是比較容易理解的,先給所有結(jié)點(diǎn)做一個(gè)false標(biāo)記辅斟,然后用for循環(huán)遍歷所有點(diǎn)標(biāo)記為false的點(diǎn)转晰,從一個(gè)點(diǎn)開始進(jìn)行bfs找到所有能找到的點(diǎn),將找到的點(diǎn)標(biāo)記為true;結(jié)果加到數(shù)組排序

代碼

  1. bfs
/**
 *  Definition for Undirected graph.
 *  class UndirectedGraphNode {
 *      int label;
 *      ArrayList<UndirectedGraphNode> neighbors;
 *      UndirectedGraphNode(int x) { 
 *          label = x;
 *          neighbors = new ArrayList<UndirectedGraphNode>(); 
 *      
 *      }
 *  }
 */


public class Solution {
    /*
     * @param nodes: a array of Undirected graph node
     * @return: a connected set of a Undirected graph
     */
    public List<List<Integer>> connectedSet(List<UndirectedGraphNode> nodes) {
        List<List<Integer>> results = new ArrayList<>();
        Map<UndirectedGraphNode, Boolean> visited = new HashMap<>();
        
        if (nodes.size() == 0) {
            return results;
        }
        
        for (int i = 0; i < nodes.size(); i++) {
            visited.put(nodes.get(i), true);
        }
        
        for (int i = 0; i < nodes.size(); i++) {
            UndirectedGraphNode node = nodes.get(i);
            if (visited.get(node) == true) {
                bfs(node, visited, results);
            }
        }
        
        return results;
    }
    
    private void bfs(UndirectedGraphNode node, 
                     Map<UndirectedGraphNode, Boolean> visited, 
                     List<List<Integer>> results) {
        Queue<UndirectedGraphNode> queue = new LinkedList<>();
        List<Integer> level = new ArrayList<>();
        
        queue.offer(node);
        visited.put(node, false);
        while (!queue.isEmpty()) {
            UndirectedGraphNode head = queue.poll();
            level.add(head.label);
            for (UndirectedGraphNode neighbor : head.neighbors) {
                if (visited.get(neighbor) == true) {
                    queue.offer(neighbor);
                    visited.put(neighbor, false);
                }
            }
        }
        Collections.sort(level);
        results.add(level);
    }
}
  1. 并查集
public
class Solution {
    class UnionFind {
        HashMap<Integer, Integer> father = new HashMap<Integer, Integer>();
        UnionFind(HashSet<Integer> hashSet)
        {
            for (Integer now : hashSet) {
                father.put(now, now);
            }
        }
        int find(int x)
        {
            int parent = father.get(x);
            while (parent != father.get(parent)) {
                parent = father.get(parent);
            }
            return parent;
        }
        int compressed_find(int x)
        {
            int parent = father.get(x);
            while (parent != father.get(parent)) {
                parent = father.get(parent);
            }
            int next;
            while (x != father.get(x)) {
                next = father.get(x);
                father.put(x, parent);
                x = next;
            }
            return parent;
        }

        void union(int x, int y)
        {
            int fa_x = find(x);
            int fa_y = find(y);
            if (fa_x != fa_y)
                father.put(fa_x, fa_y);
        }
    }
    
    List<List<Integer> > print(HashSet<Integer> hashSet, UnionFind uf, int n) {
        List<List<Integer> > ans = new ArrayList<List<Integer> >();
        HashMap<Integer, List<Integer> > hashMap = new HashMap<Integer, List<Integer> >();
        for (int i : hashSet) {
            int fa = uf.find(i);
            if (!hashMap.containsKey(fa)) {
                hashMap.put(fa, new ArrayList<Integer>());
            }
            List<Integer> now = hashMap.get(fa);
            now.add(i);
            hashMap.put(fa, now);
        }
        for (List<Integer> now : hashMap.values()) {
            Collections.sort(now);
            ans.add(now);
        }
        return ans;
    }

public
    List<List<Integer> > connectedSet(ArrayList<UndirectedGraphNode> nodes)
    {
        // Write your code here

        HashSet<Integer> hashSet = new HashSet<Integer>();
        for (UndirectedGraphNode now : nodes) {
            hashSet.add(now.label);
            for (UndirectedGraphNode neighbour : now.neighbors) {
                hashSet.add(neighbour.label);
            }
        }
        UnionFind uf = new UnionFind(hashSet);

        for (UndirectedGraphNode now : nodes) {

            for (UndirectedGraphNode neighbour : now.neighbors) {
                int fnow = uf.find(now.label);
                int fneighbour = uf.find(neighbour.label);
                if (fnow != fneighbour) {
                    uf.union(now.label, neighbour.label);
                }
            }
        }

        return print(hashSet, uf, nodes.size());
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末查邢,一起剝皮案震驚了整個(gè)濱河市蔗崎,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌扰藕,老刑警劉巖缓苛,帶你破解...
    沈念sama閱讀 216,591評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異邓深,居然都是意外死亡未桥,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門芥备,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)冬耿,“玉大人,你說(shuō)我怎么就攤上這事萌壳∠常” “怎么了?”我有些...
    開封第一講書人閱讀 162,823評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵讶凉,是天一觀的道長(zhǎng)染乌。 經(jīng)常有香客問(wèn)我,道長(zhǎng)懂讯,這世上最難降的妖魔是什么荷憋? 我笑而不...
    開封第一講書人閱讀 58,204評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮褐望,結(jié)果婚禮上勒庄,老公的妹妹穿的比我還像新娘。我一直安慰自己瘫里,他們只是感情好实蔽,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著谨读,像睡著了一般局装。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上劳殖,一...
    開封第一講書人閱讀 51,190評(píng)論 1 299
  • 那天铐尚,我揣著相機(jī)與錄音,去河邊找鬼哆姻。 笑死宣增,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的矛缨。 我是一名探鬼主播爹脾,決...
    沈念sama閱讀 40,078評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼帖旨,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了灵妨?” 一聲冷哼從身側(cè)響起碉就,我...
    開封第一講書人閱讀 38,923評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎闷串,沒(méi)想到半個(gè)月后瓮钥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,334評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡烹吵,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評(píng)論 2 333
  • 正文 我和宋清朗相戀三年碉熄,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了实愚。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片噩翠。...
    茶點(diǎn)故事閱讀 39,727評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖隆箩,靈堂內(nèi)的尸體忽然破棺而出凉蜂,到底是詐尸還是另有隱情琼梆,我是刑警寧澤,帶...
    沈念sama閱讀 35,428評(píng)論 5 343
  • 正文 年R本政府宣布窿吩,位于F島的核電站茎杂,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏纫雁。R本人自食惡果不足惜煌往,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望轧邪。 院中可真熱鬧刽脖,春花似錦、人聲如沸忌愚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)硕糊。三九已至院水,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間癌幕,已是汗流浹背衙耕。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留勺远,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,734評(píng)論 2 368
  • 正文 我出身青樓时鸵,卻偏偏與公主長(zhǎng)得像胶逢,于是被迫代替她去往敵國(guó)和親厅瞎。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容