算法题--图的深度拷贝
0. 链接
1. 题目
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<Node> 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 1:
示意图
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).
Example 2:
示意图
Input: adjList = [[]]
Output: [[]]
Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
Example 3:
Input: adjList = []
Output: []
Explanation: This an empty graph, it does not have any nodes.
Example 4:
示意图
Input: adjList = [[2],[1]]
Output: [[2],[1]]
Constraints:
1 <= Node.val <= 100
Node.val is unique for each node.
Number of Nodes will not exceed 100.
There is no repeated edges and no self-loops in the graph.
The Graph is connected and all nodes can be visited starting from the given node.
2. 思路1: 队列+BFS
- 基本思路是:
- 初始化一个队列,将任意一个节点作为起始节点,添加到队尾;初始化一个字典dic<原始节点, 拷贝节点>
- 每次从队头pop出一个节点, 然后把它的邻居节点逐个添加到队尾 这样就确保了FIFO的特性, 达成了宽度搜索
- 处理每个节点的时候, 遍历它的每个邻居, 判断它是否处理过(即在dic中有它), 如果没有, 则实施节点拷贝, 并添加到dic中; 且记录拷贝邻居节点成为当前拷贝节点的邻居
- 直至队列为空, 则由于图的连通性, 所有节点都已处理完毕
- 分析:
- 所有节点
N
都被遍历常数次, 且所有边E
都被遍历常数次, 查找是否遍历过依赖dic的O(1)查找特性, 于是时间复杂度为O(N+E)
, 空间复杂度O(N)
- 复杂度
- 时间复杂度
O(N+E)
- 空间复杂度
O(N)
3. 代码
# coding:utf8
import collections
# 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 []
# BFS
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if node is None:
return None
dic = dict()
queue = collections.deque()
node_copy = Node(node.val)
queue.append(node)
dic[node] = node_copy
while len(queue) > 0:
head = queue.popleft()
for neighbor in head.neighbors:
if neighbor not in dic:
# 遇到新节点, 则拷贝新节点内容到目标容器
neighbor_copy = Node(neighbor.val)
queue.append(neighbor)
dic[neighbor] = neighbor_copy
# 补齐head和neighbor之间的连接关系
dic[head].neighbors.append(neighbor_copy)
else:
# 补齐head和neighbor之间的连接关系
dic[head].neighbors.append(dic[neighbor])
return node_copy
def print_graph(node1):
queue = collections.deque()
queue.append(node1)
visited_set = set()
while len(queue) > 0:
head = queue.popleft()
if head in visited_set:
continue
visited_set.add(head)
neighbors = list()
for neighbor in head.neighbors:
neighbors.append(neighbor.val)
if neighbor not in visited_set:
queue.append(neighbor)
print('node.val={}, neigbors: {}'.format(head.val, neighbors))
solution = Solution()
graph1 = node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node1.neighbors += [node2, node4]
node2.neighbors += [node1, node3]
node3.neighbors += [node2, node4]
node4.neighbors += [node1, node3]
print('input:')
print_graph(graph1)
print('*' * 10)
graph1_copy = solution.cloneGraph(graph1)
print('output:')
print_graph(graph1_copy)
print('=' * 50)
输出结果
input:
node.val=1, neigbors: [2, 4]
node.val=2, neigbors: [1, 3]
node.val=4, neigbors: [1, 3]
node.val=3, neigbors: [2, 4]
**********
output:
node.val=1, neigbors: [2, 4]
node.val=2, neigbors: [1, 3]
node.val=4, neigbors: [1, 3]
node.val=3, neigbors: [2, 4]
==================================================
4. 结果
image.png5. 思路2: 栈+DFS
- 过程
- 与BFS相比, 唯一的区别是, 循环里每次都取出栈尾元素进行处理, 这样,它遍历节点的顺序就变成了紧跟节点入栈的节奏, 先找到一条到达终点的最深路径, 再处理其他路径, 即为深度优先搜索
- 分析
同BFS相同 - 时间复杂度
O(N+E)
- 空间复杂度
O(N)
6. 代码
# coding:utf8
import collections
# 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 []
# DFS
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if node is None:
return None
dic = dict()
stack = list()
node_copy = Node(node.val)
dic[node] = node_copy
stack.append(node)
while len(stack) > 0:
last = stack.pop()
for neighbor in last.neighbors:
if neighbor not in dic:
neighbor_copy = Node(neighbor.val)
stack.append(neighbor)
dic[neighbor] = neighbor_copy
dic[last].neighbors.append(dic[neighbor])
else:
dic[last].neighbors.append(dic[neighbor])
return node_copy
def print_graph(node1):
queue = collections.deque()
queue.append(node1)
visited_set = set()
while len(queue) > 0:
head = queue.popleft()
if head in visited_set:
continue
visited_set.add(head)
neighbors = list()
for neighbor in head.neighbors:
neighbors.append(neighbor.val)
if neighbor not in visited_set:
queue.append(neighbor)
print('node.val={}, neigbors: {}'.format(head.val, neighbors))
solution = Solution()
graph1 = node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node1.neighbors += [node2, node4]
node2.neighbors += [node1, node3]
node3.neighbors += [node2, node4]
node4.neighbors += [node1, node3]
print('input:')
print_graph(graph1)
print('*' * 10)
graph1_copy = solution.cloneGraph(graph1)
print('output:')
print_graph(graph1_copy)
print('=' * 50)
输出结果
input:
node.val=1, neigbors: [2, 4]
node.val=2, neigbors: [1, 3]
node.val=4, neigbors: [1, 3]
node.val=3, neigbors: [2, 4]
**********
output:
node.val=1, neigbors: [2, 4]
node.val=2, neigbors: [1, 3]
node.val=4, neigbors: [1, 3]
node.val=3, neigbors: [2, 4]
==================================================