题目链接
法一(BFS)
public Node cloneGraph(Node node) {
if (node == null) {
return null;
}
Queue<Node> queue = new LinkedList<>();
Map<Node, Node> isClone = new HashMap<>();
queue.offer(node);
isClone.put(node, new Node(node.val));
while (!queue.isEmpty()) {
Node fromNode = queue.poll();
List<Node> neighbors = fromNode.neighbors;
Node fromNodeClone = isClone.get(fromNode);
for (Node toNode : neighbors) {
if (!isClone.containsKey(toNode)) {
queue.offer(toNode);
isClone.put(toNode, new Node(toNode.val));
}
fromNodeClone.neighbors.add(isClone.get(toNode));
}
}
return isClone.get(node);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
法二(DFS)
Map<Node, Node> isClone = new HashMap<>();
public Node cloneGraph_2(Node node) {
if (node == null) {
return null;
}
Node fromNodeClone = new Node(node.val, new ArrayList<>());
isClone.put(node, fromNodeClone);
for (Node toNode : node.neighbors) {
Node toNodeClone = isClone.get(toNode);
if (toNodeClone == null) {
toNodeClone = cloneGraph_2(toNode);
}
fromNodeClone.neighbors.add(toNodeClone);
}
return fromNodeClone;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
本地测试
lay.showTitle(133);
Solution133 sol133 = new Solution133();
Integer[][] adjArr133 = new Integer[][]{{2, 4}, {1, 3}, {2, 4}, {1, 3}};
List<List<Integer>> adjList133 = Arrays.stream(adjArr133).map(Arrays::asList).collect(Collectors.toList());
undirectedGraph.Node firstVertex133 = undirectedGraphOpt.createGraph(adjList133);
undirectedGraphOpt.BFSTraversal(firstVertex133);
undirectedGraph.Node cloneVertex133_1 = sol133.cloneGraph(firstVertex133);
undirectedGraphOpt.BFSTraversal(cloneVertex133_1);
undirectedGraph.Node cloneVertex133_2 = sol133.cloneGraph_2(firstVertex133);
undirectedGraphOpt.BFSTraversal(cloneVertex133_2);