算法題--圖的深度拷貝

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: 隊(duì)列+BFS

  1. 基本思路是:
  • 初始化一個(gè)隊(duì)列蜗帜,將任意一個(gè)節(jié)點(diǎn)作為起始節(jié)點(diǎn),添加到隊(duì)尾博脑;初始化一個(gè)字典dic<原始節(jié)點(diǎn), 拷貝節(jié)點(diǎn)>
  • 每次從隊(duì)頭pop出一個(gè)節(jié)點(diǎn), 然后把它的鄰居節(jié)點(diǎn)逐個(gè)添加到隊(duì)尾 這樣就確保了FIFO的特性, 達(dá)成了寬度搜索
  • 處理每個(gè)節(jié)點(diǎn)的時(shí)候, 遍歷它的每個(gè)鄰居堪遂, 判斷它是否處理過(guò)(即在dic中有它), 如果沒(méi)有, 則實(shí)施節(jié)點(diǎn)拷貝, 并添加到dic中卷拘; 且記錄拷貝鄰居節(jié)點(diǎn)成為當(dāng)前拷貝節(jié)點(diǎn)的鄰居
  • 直至隊(duì)列為空, 則由于圖的連通性, 所有節(jié)點(diǎn)都已處理完畢
  1. 分析:
  • 所有節(jié)點(diǎn)N都被遍歷常數(shù)次, 且所有邊E都被遍歷常數(shù)次, 查找是否遍歷過(guò)依賴(lài)dic的O(1)查找特性, 于是時(shí)間復(fù)雜度為O(N+E), 空間復(fù)雜度O(N)
  1. 復(fù)雜度
  • 時(shí)間復(fù)雜度 O(N+E)
  • 空間復(fù)雜度 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:
                    # 遇到新節(jié)點(diǎn), 則拷貝新節(jié)點(diǎn)內(nèi)容到目標(biāo)容器
                    neighbor_copy = Node(neighbor.val)
                    queue.append(neighbor)
                    dic[neighbor] = neighbor_copy
                    # 補(bǔ)齊head和neighbor之間的連接關(guān)系
                    dic[head].neighbors.append(neighbor_copy)
                else:
                    # 補(bǔ)齊head和neighbor之間的連接關(guān)系
                    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)

輸出結(jié)果

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. 結(jié)果

image.png

5. 思路2: 棧+DFS

  1. 過(guò)程
  • 與BFS相比氢橙, 唯一的區(qū)別是, 循環(huán)里每次都取出棧尾元素進(jìn)行處理, 這樣,它遍歷節(jié)點(diǎn)的順序就變成了緊跟節(jié)點(diǎn)入棧的節(jié)奏, 先找到一條到達(dá)終點(diǎn)的最深路徑, 再處理其他路徑, 即為深度優(yōu)先搜索
  1. 分析
    同BFS相同
  2. 時(shí)間復(fù)雜度 O(N+E)
  3. 空間復(fù)雜度 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)

輸出結(jié)果

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. 結(jié)果

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末甩鳄,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子额划,更是在濱河造成了極大的恐慌妙啃,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件俊戳,死亡現(xiàn)場(chǎng)離奇詭異揖赴,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)抑胎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)燥滑,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人阿逃,你說(shuō)我怎么就攤上這事铭拧。” “怎么了恃锉?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵搀菩,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我破托,道長(zhǎng)肪跋,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任土砂,我火速辦了婚禮州既,結(jié)果婚禮上谜洽,老公的妹妹穿的比我還像新娘。我一直安慰自己吴叶,他們只是感情好褥琐,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著晤郑,像睡著了一般敌呈。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上造寝,一...
    開(kāi)封第一講書(shū)人閱讀 51,562評(píng)論 1 305
  • 那天磕洪,我揣著相機(jī)與錄音,去河邊找鬼诫龙。 笑死析显,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的签赃。 我是一名探鬼主播谷异,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼锦聊!你這毒婦竟也來(lái)了歹嘹?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤孔庭,失蹤者是張志新(化名)和其女友劉穎尺上,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體圆到,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡怎抛,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了芽淡。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片马绝。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖挣菲,靈堂內(nèi)的尸體忽然破棺而出富稻,到底是詐尸還是另有隱情,我是刑警寧澤己单,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布唉窃,位于F島的核電站,受9級(jí)特大地震影響纹笼,放射性物質(zhì)發(fā)生泄漏纹份。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蔓涧。 院中可真熱鬧件已,春花似錦、人聲如沸元暴。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)茉盏。三九已至鉴未,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間鸠姨,已是汗流浹背铜秆。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留讶迁,地道東北人连茧。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像巍糯,于是被迫代替她去往敵國(guó)和親啸驯。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355