算法学习

算法题--图的深度拷贝

2020-05-07  本文已影响0人  岁月如歌2020
image.png

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

  1. 基本思路是:
  1. 分析:
  1. 复杂度

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.png

5. 思路2: 栈+DFS

  1. 过程
  1. 分析
    同BFS相同
  2. 时间复杂度 O(N+E)
  3. 空间复杂度 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]
==================================================

7. 结果

image.png
上一篇下一篇

猜你喜欢

热点阅读