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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。