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 #
.
- 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 / \_/
Copy the non-circular band diagram.
Idea: recursively traverse each vertex according to the depth search, and the result is a sub-graph that returns the starting point at the critical point. To consider the case with a loop, but also to avoid the same node access multiple times, the map can be used to judge the weight.
Static class Undirectedgraphnode {int label; List<undirectedgraphnode> Neighbors; Undirectedgraphnode (int x) {label = x; Neighbors = new Arraylist<undirectedgraphnode> (); }} static public Undirectedgraphnode Dfs (undirectedgraphnode node, Map<integer, undirectedgraphnode> Vis) { if (node! = null && vis.get (node.label) = = null) {Undirectedgraphnode CloneNode = new undirected Graphnode (Node.label); Vis.put (Node.label, CloneNode); Clonenode.neighbors = new Arraylist<undirectedgraphnode> (Node.neighbors.size ()); for (int i = 0; i < node.neighbors.size (); i++) {CloneNode.neighbors.add (Dfs (Node.neighbors.get (i), Vis )); } return CloneNode; } else if (node = = null) {return node; } else {//deal If the graph has a circle return Vis.get (Node.label); }} STATic public undirectedgraphnode Clonegraph (Undirectedgraphnode node) {Map<integer, undirectedgraphnode> vis = New Hashmap<integer, undirectedgraphnode> (); Return DFS (node, VIS); } public static void Main (string[] args) {undirectedgraphnode node = new Undirectedgraphnode (0); Node.neighbors.add (node); System.out.println (node.neighbors.get (0) = = node); Undirectedgraphnode clone = clonegraph (node); System.out.println (Clone.label); }
Copy the non-circular band diagram