1. 题目描述
2. Solution 1
1、思路分析
DFS
2、代码实现
package Q0199.Q0133CloneGraph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/*
DFS
*/
public class Solution {
private Map<Integer, Node> seen = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) return null;
if (seen.containsKey(node.val)) return seen.get(node.val);
Node newNode = new Node(node.val, new ArrayList<>());
seen.put(newNode.val, newNode);
for (Node neighbor : node.neighbors)
newNode.neighbors.add(cloneGraph(neighbor));
return newNode;
}
}
3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(n)
3. Solution 2
1、思路分析
BFS
2、代码实现
package Q0199.Q0133CloneGraph;
import java.util.*;
/*
BFS:
*/
public class Solution2 {
private Map<Node, Node> seen = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) return null;
Node copy = new Node(node.val, new ArrayList<>());
seen.put(node, copy);
Queue<Node> queue = new arraydeque<>();
queue.add(node);
while (!queue.isEmpty()) {
Node cur = queue.poll();
for (Node neighbor : cur.neighbors) {
if (!seen.containsKey(neighbor)) {
seen.put(neighbor, new Node(neighbor.val, new ArrayList<>()));
queue.add(neighbor);
}
seen.get(cur).neighbors.add(seen.get(neighbor));
}
}
return copy;
}
}
3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(n)