题目
给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。
图中的每个节点都包含它的值 val(int) 和其邻居的列表(list[Node])。
链接:https://leetcode.com/problems/clone-graph/
Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.
class Node {
public int val;
public List neighbors;
}
Test case format:
For simplicity sake, each node’s value is the same as the node’s index (1-indexed). For example, the first node with val = 1, the second node with val = 2, and so on. The graph is represented in the test case using an adjacency list.
Adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.
Example:
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
思路及代码
- 输入是一个node
- neighbor里元素的格式也是node
DFS
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
dic = {}
def dfs(node):
if not node:
return
new = Node(node.val, [])
dic[node] = new
for nei in node.neighbors:
if nei not in dic:
new.neighbors.append(dfs(nei))
else:
new.neighbors.append(dic[nei])
return new
return dfs(node)
BFS
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return
dic = {}
new = Node(node.val, [])
queue = [node]
dic[node] = new
while queue:
n = queue.pop(0)
for nei in n.neighbors:
if nei in dic:
dic[n].neighbors.append(dic[nei])
else:
neiCopy = Node(nei.val, [])
dic[nei] = neiCopy
dic[n].neighbors.append(neiCopy)
queue.append(nei)
return new
复杂度
T =
O
(
V
+
E
)
O(V+E)
O(V+E)
S =
O
(
V
+
E
)
O(V+E)
O(V+E)