1. 程式人生 > 其它 >【1月打卡~Leetcode每日一題】547. 省份數量(難度:中等)

【1月打卡~Leetcode每日一題】547. 省份數量(難度:中等)

技術標籤:演算法python演算法資料結構機器學習

547. 省份數量

有 n 個城市,其中一些彼此相連,另一些沒有相連。如果城市 a 與城市 b 直接相連,且城市 b 與城市 c 直接相連,那麼城市 a 與城市 c 間接相連。
省份 是一組直接或間接相連的城市,組內不含其他沒有相連的城市。
給你一個 n x n 的矩陣 isConnected ,其中 isConnected[i][j] = 1 表示第 i 個城市和第 j 個城市直接相連,而 isConnected[i][j] = 0 表示二者不直接相連。
返回矩陣中 省份 的數量。

方法一:DFS

class Solution:
    def
findCircleNum(self, isConnected: List[List[int]]) -> int: n,ans = len(isConnected),0 visited = set() def dfs(i): visited.add(i) for j in range(n): if isConnected[i][j]==1 and j not in visited: dfs(j) for
i in range(n): if i not in visited: ans += 1 dfs(i) return ans

時間複雜度O(n²)
空間複雜度O(n)

方法二:並查集(模版建議背下來)
find函式:找某個數所在宗族的族地,union函式:將index1的族地改成index2的族地,最後返回當前數即自己族地的數量,即連通域個數

class Solution:
    def findCircleNum(self, isConnected: List[List[int
]]) -> int: n = len(isConnected) parent = list(range(n)) def find(index): if parent[index] != index: parent[index] = find(parent[index]) return parent[index] def union(index1,index2): parent[find(index1)] = find(index2) for i in range(n): for j in range(i): if isConnected[i][j]: union(i,j) return sum(parent[i]==i for i in range(n))