Leetcode 323. Number of Connected Components in an Undirected Graph(python+cpp)

Leetcode 323. Number of Connected Components in an Undirected Graph

  • 题目
  • 解法1:DFS
  • 解法2:unionfind

题目

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.
Leetcode 323. Number of Connected Components in an Undirected Graph(python+cpp)_第1张图片

解法1:DFS

  • 每次DFS除去一条联通路,并且将DFS过程中已经访问过的节点放入set中
  • 若当前访问的节点在之前的路径中已经被访问,证明当前节点属于已经产生的联通路中
  • 否则从这个节点开始开辟一条新路径
class Solution:
    def countComponents(self, n: int, edges: List[List[int]]) -> int:
        helper(u):
            if u in pair:
                for v in pair[u]:
                    if v not in visited:
                        visited.add(v)
                        helper(v)
            
        pair = collections.defaultdict(set)
        for u,v in edges:
            pair[u].add(v)
            pair[v].add(u)
        count = 0
        visited = set()
        for i in range(n):
            if i not in visited:
                helper(i)
                count+=1
        return count

时间复杂度:O(E), E为边的条数
空间复杂度:O(E+N),N为节点个数

解法2:unionfind

解析参见代码注释

class Solution:
    def countComponents(self, n: int, edges: List[List[int]]) -> int:
        def unionfind(p1,p2):
            nonlocal count
            # find root of p1
            while root[p1]!=p1:
                p1 = root[p1]
            # find root of p2
            while root[p2]!=p2:
                p2 = root[p2]
            #if roots of p1 and p2 are identicle, meaning they have already been merged
            if root[p1]==root[p2]:
                return
            # merge them if not merged 
            else:
                root[p1] = p2
                count -= 1
        # initially, we have n connected path
        count = n 
        # store original roots
        root = [i for i in range(n)] 
        # go through each node pair
        for edge in edges:
            unionfind(edge[0],edge[1])
        return count

时间复杂度:有点想不清,欢迎留言
空间复杂度:O(N),N为节点个数

你可能感兴趣的:(Leetcode,DFS,dfs,leetcode)