Clone Graph
Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
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 by #
.
- First node is labeled as
0
. Connect node0
to both nodes1
and2
. - Second node is labeled as
1
. Connect node1
to node2
. - Third node is labeled as
2
. Connect node2
to node2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
这道题题目有点长,略微有点烦。这道题思路还是比较简单,直接用DFS或者BFS可以A
这里我用的是DFS
ps:剩下leetcode上面的hard类型了
1 import java.util.ArrayList; 2 3 import java.util.Hashtable; 4 import java.util.List; 5 6 public class Solution { 7 public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { 8 if(null == node) 9 return node; 10 boolean isFirst = true; 11 Hashtable<UndirectedGraphNode, Integer> visited = new Hashtable<UndirectedGraphNode, Integer>(); 12 Hashtable<UndirectedGraphNode, UndirectedGraphNode> map = new Hashtable<UndirectedGraphNode, UndirectedGraphNode>(); 13 14 DFS(node, visited, map, isFirst); 15 16 visited = new Hashtable<UndirectedGraphNode, Integer>(); 17 isFirst = false; 18 DFS(node, visited, map, isFirst); 19 20 return map.get(node); 21 22 } 23 24 private void DFS(UndirectedGraphNode node, Hashtable<UndirectedGraphNode, Integer> visited, 25 Hashtable<UndirectedGraphNode, UndirectedGraphNode> map, boolean isFirst){ 26 if(visited.get(node) == null){ 27 if(isFirst){ 28 UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); 29 map.put(node, newNode); //key为旧的引用,value为新的引用 30 } 31 32 //深度遍历 33 List<UndirectedGraphNode> neighborsList = node.neighbors; 34 visited.put(node, 1); //标记为已访问 35 for(UndirectedGraphNode nodeInList : neighborsList){ 36 if(isFirst){ //第一次遍历 37 DFS(nodeInList, visited, map, isFirst); 38 }else{ //第二次遍历 39 if(map.get(node).neighbors == null) 40 map.get(node).neighbors = new ArrayList<UndirectedGraphNode>(); 41 map.get(node).neighbors.add(map.get(nodeInList)); 42 DFS(nodeInList, visited, map, isFirst); 43 } 44 } 45 } 46 else 47 return; 48 } 49 }
Please call me JiangYouDang!