項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 search-input 尚未註冊或是沒有一個 view.php 檔案.

【Lintcode】python – [431] Connected Component in Undirected Graph 個人解法筆記 | 內含 BFS 模板 (updated: 2022/6/8) #重要題型

題目出處

431 · Connected Component in Undirected Graph

難度

medium

個人範例程式碼 – 2022/6/8 三刷

from typing import (
    List,
)
from lintcode import (
    UndirectedGraphNode,
)

"""
class UndirectedGraphNode:
     def __init__(self, x):
         self.label = x
         self.neighbors = []
"""

class Solution:
    """
    @param nodes: a array of Undirected graph node
    @return: a connected set of a Undirected graph
    """
    def connectedSet(self, nodes: List[UndirectedGraphNode]) -> List[List[int]]:
        # write your code here
        if not nodes:
            return nodes

        visited = set()
        ans = []
        for node in nodes:
            if node not in visited:
                ans.append(self.get_connected_parts(nodes, visited, node))

        return ans

    def get_connected_parts(self, nodes, visited, start_node):
        queue = [start_node]
        ans = []
        visited.add(start_node)

        while queue:
            node = queue.pop(0)
            ans.append(node.label)
            for neighbor in node.neighbors:
                if neighbor not in visited:
                    queue.append(neighbor)
                    visited.add(neighbor)

        return sorted(ans)

算法說明

BFS 搜尋圖,並把同一組的歸類再一起。

input handling

x

Boundary conditions

用 for 配合 visited 來尋找 start_node,
bfs 內部用 queue 來掌控搜尋範圍。

個人範例程式碼 – 2022/6/7 二刷

from typing import (
    List,
)
from lintcode import (
    UndirectedGraphNode,
)

"""
class UndirectedGraphNode:
     def __init__(self, x):
         self.label = x
         self.neighbors = []
"""

class Solution:
    """
    @param nodes: a array of Undirected graph node
    @return: a connected set of a Undirected graph
    """
    def connectedSet(self, nodes: List[UndirectedGraphNode]) -> List[List[int]]:
        # write your code here

        visited = set()
        ans = []
        for node in nodes:
            if node not in visited:
                ans.append(self.bfs(nodes, node, visited))

        return ans

    def bfs(self, nodes, start_node, visited):
        ans = []
        queue = [start_node]
        visited.add(start_node)

        while queue:
            node = queue.pop(0)
            ans.append(node.label)
            for neighbor in node.neighbors:
                if neighbor not in visited:
                    queue.append(neighbor)
                    visited.add(neighbor)

        return sorted(ans)

算法說明

BFS 搜尋圖,並把同一組的歸類再一起。

input handling

x

Boundary conditions

用 for 配合 visited 來尋找 start_node,
bfs 內部用 queue 來掌控搜尋範圍。

個人範例程式碼 – 2022/6/1 一刷

from typing import (
    List,
)
from lintcode import (
    UndirectedGraphNode,
)

"""
class UndirectedGraphNode:
     def __init__(self, x):
         self.label = x
         self.neighbors = []
"""

class Solution:
    """
    @param nodes: a array of Undirected graph node
    @return: a connected set of a Undirected graph
    """
    def connectedSet(self, nodes: List[UndirectedGraphNode]) -> List[List[int]]:
        # write your code here
        if not nodes:
            return []

        ans = []
        visited = set()
        for node in nodes:
            if node in visited:
                continue
            visited.add(node)
            ans.append(self.bfs(node, visited))

        return ans

    def bfs(self, start_node, visited):
        ans = []
        queue = [start_node]
        while(queue):
            node = queue.pop(0)
            ans.append(node.label)
            for neighbor in node.neighbors: # add all not visited neighbor
                if neighbor not in visited:
                    queue.append(neighbor)
                    visited.add(neighbor)

        return sorted(ans)

算法說明

經典的 bfs 問題,可以複製此架構變化的 BFS 題目很多。

最外圈,先透過 for 確保所有 node 都會被搜尋,再搭配上 visited,確保不重複搜尋。
內圈的 BFS,我們透過 while 不斷地新增 nighbor,直到 visited 全滿不能再新增,就結束回傳答案。

由於題目有要求回傳的答案要是 sorted,請注意先 sorted 後再回傳。

input handling

處理沒有 input 的情況,return []

Boundary conditions

用 for 配合 visited 來尋找 start nod