[Leetcod] Clone Graph

Source: Internet
Author: User

title :

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


OJ ' s undirected graph serialization:

Nodes is labeled uniquely.

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

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

    1. First node is labeled as 0 . Connect node to 0 both nodes 1 and 2 .
    2. Second node is labeled as 1 . Connect node to 1 node 2 .
    3. 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/\_/


puzzle:
Reference: Http://www.cnblogs . com/springfor/p/3874591.html
This topic examines the way in which graphs are traversed and used hashmap copies. The
traversal of the graph is a two classic method of Dfs and BFS. BFS is often implemented with queue, and DFS is often implemented recursively (can be changed to stack implementation). The
Copy method uses the value of Hashmap,key to store the original value, value of copy, and the Dfs,bfs method to traverse the value of the Help copy neighbors.

Review Dfs and BFS first.

DFS (Dpeth-first search)
As the name implies, is deep search, a road to the black, and then choose a new way.
Remember when algorithm, the professor cited the example is that Dfs is like a curious child, you give the child a box of boxes, curious children will certainly be a box open and continue to search in this box.
Wait until the box is open, then open the second set.
Wikipedia explains: " Depth-first search ( DFS ) is a algorithm for traversing or Searching tree or graph data structures.
One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as Possi BLE
along each branch before backtracking. "
usually a simple DFS notation is recursive, and if it is not recursive, it is the stack iteration, the idea is the same. The
recursive code for DFS pseudocode is as follows:
Input : A graph G and a root v of G
1 procedure DFS (G,V):
2 Label V as discovered
3 for all edges from V to W in G.adjacentedges (v) do
4 If vertex w isn't labeled as discovered then
5 recursively call DFS (G,W)
The DFS pseudo-code for non-recursive notation is as follows:
Input G v of G
1 procedure dfs-iterative (G,V):
2 Let S be a stack
3 S.push (v)
4 while S isn't empty
5 V←s.pop ()
6 if V is not labeled as discovered:
7 Label V as discovered
8 for all edges from V to W in G.adjacentedges (v) do
9 S.push (W)



BFS (Breadth-first Search)
This is the relative to the bfs of the other way of traversing the graph, for a node to first check all neighbors, and then start from the first neighbor, the cycle.
Because of this characteristic of BFS, BFS can help find the shortest path.
Wikipedia's definition of BFS above is:
Breadth-first Search (BFS
Iterative deepening Depth-first search and contrast with Depth-first search. "

Typically BFS is implemented with queue+ loops, with pseudocode as follows:
Input G v of G
1 procedure BFS (G,V) is
2 Create a queue Q
3 Create a set V
4 Add V to V
5 Enqueue v onto Q
6 while Q isn't empty loop
7 T←q.dequeue ()
8 If T is looking
9 Return T
Ten End If
Edges e in g.adjacentedges (t) loop
U←g.adjacentvertex (T,e)
If you are not at V then
Add U to V
Enqueue u onto Q
End If
+ END Loop
End Loop
return None
End BFS
*************************************************************************************************************** *****************
Here are 3 ways to solve this problem.

The first method of implementation is BFS, is to first put the head node into the queue, each queue out of a node, and then check the node all the neighbors, if not visited, the team, and update neighbor.
Then update the new neighbor list.
The code is as follows:
1 public undirectedgraphnode Clonegraph (Undirectedgraphnode node) {
2 if (node = = null)
3 return null;
4
5 Hashmap<undirectedgraphnode, undirectedgraphnode> HM = new Hashmap<undirectedgraphnode, UndirectedGraph Node> ();
6 linkedlist<undirectedgraphnode> queue = new linkedlist<undirectedgraphnode> ();
7 Undirectedgraphnode head = new Undirectedgraphnode (Node.label);
8 Hm.put (node, head);
9 Queue.add (node);
10
One while (!queue.isempty ()) {
Undirectedgraphnode Curnode = Queue.poll ();
(Undirectedgraphnode aneighbor:curnode.neighbors) {//check each neighbor
if (!hm.containskey (Aneighbor)) {//if not visited,then add to queue
Queue.add (Aneighbor);
Undirectedgraphnode Newneighbor = new Undirectedgraphnode (Aneighbor.label);
Hm.put (Aneighbor, Newneighbor);
18}
19
Hm.get (Curnode). Neighbors.add (Hm.get (Aneighbor));
21}
22}
23
return head;
25}
The recursive operation of Dfs is as follows, iterative replication neighbors:
1 public undirectedgraphnode Clonegraph (Undirectedgraphnode node) {
2 if (node = = null)
3 return null;
4
5 Hashmap<undirectedgraphnode, undirectedgraphnode> HM = new Hashmap<undirectedgraphnode, UndirectedGraph Node> ();
6 Undirectedgraphnode head = new Undirectedgraphnode (Node.label);
7 Hm.put (node, head);
8
9 DFS (HM, node);//dfs
Ten return head;
11}
public void DFS (Hashmap<undirectedgraphnode, undirectedgraphnode> hm, Undirectedgraphnode node) {
if (node = = null)
return;
15
for (Undirectedgraphnode aneighbor:node.neighbors) {
if (!hm.containskey (Aneighbor)) {
Undirectedgraphnode Newneighbor = new Undirectedgraphnode (Aneighbor.label);
Hm.put (Aneighbor, Newneighbor);
DFS (HM, Aneighbor);//dfs
21}
Hm.get (node) neighbors.add (Hm.get (Aneighbor));
23}
24}


The following method is a non-recursive Dfs method, the midpoint is the BFS in the queue into a stack, because the Dequeue method is different, so the traversal of the line is not the same. The code is as follows:
1 public undirectedgraphnode Clonegraph (Undirectedgraphnode node) {
2 if (node = = null)
3 return null;
4
5 Hashmap<undirectedgraphnode, undirectedgraphnode> HM = new Hashmap<undirectedgraphnode, UndirectedGraph Node> ();
6 linkedlist<undirectedgraphnode> stack = new linkedlist<undirectedgraphnode> ();
7 Undirectedgraphnode head = new Undirectedgraphnode (Node.label);
8 Hm.put (node, head);
9 Stack.push (node);
10
One while (!stack.isempty ()) {
Undirectedgraphnode Curnode = Stack.pop ();
(Undirectedgraphnode aneighbor:curnode.neighbors) {//check each neighbor
if (!hm.containskey (Aneighbor)) {//if not visited,then push to stack
Stack.push (Aneighbor);
Undirectedgraphnode Newneighbor = new Undirectedgraphnode (Aneighbor.label);
Hm.put (Aneighbor, Newneighbor);
18}
19
Hm.get (Curnode). Neighbors.add (Hm.get (Aneighbor));
21}
22}
23
return head;
25}

[Leetcod] Clone Graph

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.