[Question]
Clone an undirected graph. each node in the graph containslabel
And a list of itsneighbors
.
OJ's undirected graph serialization:
Nodes are 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#
.
- First node is labeled
0
. Connect Node0
To both nodes1
And2
.
- Second node is labeled
1
. Connect Node1
To Node2
.
- Third node is labeled
2
. Connect Node2
To Node2
(Itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / / 0 --- 2 / \_/
[Idea]
This question is mainly about the application of data structures. A queue is used to store unaccessed nodes in the graph, and a map is used to store new cloned nodes. For nodes in the queue, access the neighbor. If the neighbor has been cloned, you only need to maintain the Neighbor Relationship Between the clone nodes. If the neighbor has not been cloned, A new node is required as its clone, and the cloned neighbor relationship is maintained.
[Java code]
/*** Definition for undirected graph. * class undirectedgraphnode {* int label; * List <undirectedgraphnode> neighbors; * undirectedgraphnode (int x) {label = x; neighbors = new arraylist <undirectedgraphnode> ();}*}; */public class solution {public undirectedgraphnode clonegraph (undirectedgraphnode node) {If (node = NULL) return NULL; undirectedgraphnode clone = new undirectedgraphnode (node. l Abel); // use a map to save the cloned new node hashmap <integer, undirectedgraphnode> map = new hashmap <integer, undirectedgraphnode> (); map. put (node. label, clone); // use a queue to save the unaccessed node queue list <undirectedgraphnode> queue = new queue list <undirectedgraphnode> (); queue. add (node); While (! Queue. isempty () {undirectedgraphnode originalnode = queue. remove (); undirectedgraphnode clonenode = map. get (originalnode. label); For (INT I = 0; I <originalnode. neighbors. size (); I ++) {undirectedgraphnode neighbor = originalnode. neighbors. get (I); // If the neighbor node has been cloned if (map. get (neighbor. label )! = NULL) {clonenode. neighbors. add (map. get (neighbor. label); continue;} // put this neighbor into the queue. add (neighbor); // clone the neighbor node undirectedgraphnode newnode = new undirectedgraphnode (neighbor. label); // Add the new node to map. put (neighbor. label, newnode); // Add the new node to the clonenode In the neighbor set. neighbors. add (newnode) ;}} return clone ;}}
[Leetcode] clone graph solution report