成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

[LintCode/LeetCode] Clone Graph [BFS/DFS]

fredshare / 463人閱讀

摘要:開始看這道題目的時候,沒有看懂和的作用。然后對這個放入的結(jié)點開始操作遍歷的所有,當前遍歷到的的叫做。當完成,則中沒有新的結(jié)點了,退出循環(huán)。返回在中更新過的,結(jié)束。

Problem

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.

return a deep copied graph.

Example

How we serialize an undirected graph.
Nodes are labeled uniquely.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:

   1
  / 
 /   
0 --- 2
     / 
     \_/

Note

開始看這道題目的時候,沒有看懂queue和hashmap的作用。
復制一個無向圖,先分析圖的結(jié)構(gòu):label相當于圖結(jié)點的value,而neighbors相當于圖結(jié)點的所有next。然后考慮用什么方式復制:用queue用來標記當前正在復制的或已經(jīng)復制過的結(jié)點cur,而hashmap用來進行對新建無向圖結(jié)點root進行復制labelneighbors的操作。首先,從node結(jié)點開始,放入queue。然后對這個放入queue的結(jié)點cur開始操作:遍歷cur的所有neighbors,當前遍歷到的的neighbors叫做next。若map中不存在這個點,即沒有被復制過,就在map中復制這個結(jié)點nextlabel,同時存入queue以便在下次循環(huán)取出并復制其neighbors;無論map中包不包含這個neighbors結(jié)點next,都要將next加入map中對應(yīng)新建結(jié)點rootneighbors。當BFS完成,則queue中沒有新的結(jié)點了,退出while循環(huán)。返回在map中更新過的root,結(jié)束。
map.get(cur).neighbors.add(map.get(next));
這一句可以理解為,在for循環(huán)對curneighbors的遍歷中,先在HashMap里的root中建立新結(jié)點next,再將next放進root的結(jié)點curneighbors里。

Solution
// Definition for undirected graph.
class UndirectedGraphNode {
    int label;ArrayList neighbors;
    UndirectedGraphNode(int x) { 
        label = x; 
        neighbors = new ArrayList(); 
    }
}
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) return null;
        UndirectedGraphNode root = new UndirectedGraphNode(node.label);//復制根節(jié)點
        Queue queue = new LinkedList<>();
        Map map = new HashMap<>();
        queue.offer(node);//queue放入根結(jié)點
        map.put(node, root);//map放入根結(jié)點和它的復制結(jié)點
        while (!queue.isEmpty()) {
            UndirectedGraphNode cur = queue.poll();//取出queue中(同一層)的結(jié)點進行BFS
            for (UndirectedGraphNode n: cur.neighbors) {
                //對沒有復制過的結(jié)點進行復制,并將這個結(jié)點放入queue
                if (!map.containsKey(n)) {
                    map.put(n, new UndirectedGraphNode(n.label));
                    queue.offer(n);
                }
                //連接復制結(jié)點和復制neighbor結(jié)點
                map.get(cur).neighbors.add(map.get(n));
            }
        }
        return root;
    }
}
Update 2018-9 BFS
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) return node;

        Map map = new HashMap<>();
        map.put(node, new UndirectedGraphNode(node.label));                     //: <原結(jié)點, 復制結(jié)點>
        
        Queue queue = new LinkedList<>();
        queue.offer(node);                                                      //copy過的結(jié)點存入queue,以繼續(xù)遍歷其neighbor結(jié)點
        
        while (!queue.isEmpty()) {
            UndirectedGraphNode cur = queue.poll();                             //取出copy過的結(jié)點,繼續(xù)復制其所有neighbor結(jié)點
            for (UndirectedGraphNode neighbor: cur.neighbors) {
                if (!map.containsKey(neighbor)) {                               //若結(jié)點未復制過,copy后存入queue
                    map.put(neighbor, new UndirectedGraphNode(neighbor.label));
                    queue.offer(neighbor);
                }
                map.get(cur).neighbors.add(map.get(neighbor));                  //將每個copied neighbor存入copied parent node
            }
        }
        return map.get(node);                                                   //返回copied根節(jié)點
    }
}

DFS

public class Solution {
   public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        Map map = new HashMap<>();
        return cloneNode(node, map);
    }
    private UndirectedGraphNode cloneNode(UndirectedGraphNode node, Map map) {
        if (node == null) return node;
        if (map.containsKey(node)) {
            return map.get(node);
        } else {
            UndirectedGraphNode nodeCopy = new UndirectedGraphNode(node.label);
            map.put(node, nodeCopy);
            for (UndirectedGraphNode child : node.neighbors) {
                nodeCopy.neighbors.add(cloneNode(child, map));
            }
            return nodeCopy;
        }
    }
}

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/65729.html

相關(guān)文章

  • LeetCode 133:克隆圖 Clone Graph

    摘要:解題思路涉及到圖的遍歷無非就是深度優(yōu)先搜索廣度優(yōu)先搜索,可以先看前幾日的這篇文章就需要借助隊列實現(xiàn),可以借助棧也可以直接用遞歸實現(xiàn)。 題目: 給定無向連通圖中一個節(jié)點的引用,返回該圖的深拷貝(克?。?。圖中的每個節(jié)點都包含它的值 val(Int) 和其鄰居的列表(list[Node])。 Given a reference of a node in a connected undirec...

    Simon 評論0 收藏0
  • BFS,DFS 算法原理及js實現(xiàn)

    1. 說明 本文所有的算法嚴格按照《算法導論》,本文將詳細的對BFS和DFS進行分析,并提供算法的 js 實現(xiàn),同時會對創(chuàng)建鏈表的方式進行優(yōu)化 2. 圖的表示 圖的表示分為對頂點集 V 的表示和對邊集 E 的表示,這里的重點是如何表示邊,邊的表示分為鄰接矩陣和鄰接鏈表這兩種表示方法,鄰接矩陣適合表示邊稠密的圖,其消耗空間為|V|*|V|,如果是無向圖,則可以用上三角矩陣或者下三角矩陣來表示,是空間...

    劉德剛 評論0 收藏0
  • 拓撲排序原理分析及js實現(xiàn)

    摘要:但是一個偏序關(guān)系,如果我們默認,先出現(xiàn)的排在前面,那么我們就能比較,的關(guān)系了。對于算法的每個節(jié)點,我們都有一個發(fā)現(xiàn)時間,一個訪問時間,當運行完成時,對于圖中的任意一條邊,都有所以拓撲排序的次序與頂點的完成時間恰好相反。 1. 偏序和全序的概念 1.1. 偏序 設(shè)R是集合A上的一個二元關(guān)系,若R滿足下列三個性質(zhì)則稱R為A上的偏序關(guān)系自反性:對任意x∈A,有∈R反對稱性:對任意的x,y∈A...

    QiShare 評論0 收藏0
  • [LeetCode] 490. The Maze (BFS/DFS)

    Problem There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it wont stop rolling until hitting a wall. When the ball sto...

    smartlion 評論0 收藏0
  • 最小生成樹原理及Kruskal算法的js實現(xiàn)

    摘要:生成樹和最小生成樹的概念設(shè)圖連通,則生成樹包含圖中的所有節(jié)點,及條邊的連通圖,一個圖的生成樹可以有多顆最小生成樹最小權(quán)重生成樹,在生成樹的概念上加一個限制條件,即生成樹的所有邊的權(quán)值總和最小的樹,最小生成樹也可以有多顆求解最小生成樹的通用 1. 生成樹和最小生成樹的概念 設(shè)圖G(V,E)連通,則生成樹:包含圖G(V,E)中的所有節(jié)點,及|V|-1條邊的連通圖,一個圖的生成樹可以有多顆最...

    scq000 評論0 收藏0

發(fā)表評論

0條評論

fredshare

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<