Leetcode
Graph
Depth-first Search
Breath-first Search
Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains a label
(int
) and a list (List[UndirectedGraphNode]
) of its neighbors. There is an edge between the given node and each of the nodes in its neighbors.
private static class UndirectedGraphNode { int label; List<UndirectedGraphNode> neighbors; UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<>(); } }
分析¶
DFS,需要注意的是要把克隆的节点放入哈希表中,如果某一节点已经克隆,则直接返回该节点。
public class Solution { public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { HashMap<Integer, UndirectedGraphNode> map = new HashMap<>(); return clone(node, map); } private UndirectedGraphNode clone(UndirectedGraphNode node, HashMap<Integer, UndirectedGraphNode> map) { if (node == null) return null; if (map.containsKey(node.label)) return map.get(node.label); UndirectedGraphNode clone = new UndirectedGraphNode(node.label); map.put(clone.label, clone); for (UndirectedGraphNode neighbor : node.neighbors) clone.neighbors.add(clone(neighbor, map)); return clone; } }
近期评论