DevPath

← All problems

Count Connected Components

Medium graphs · union-find

Description

Given n nodes labelled 0..n-1 and an undirected edge list, return the number of connected components.

Constraints

1 <= n <= 100000

Examples

Input: n = 5, edges = [[0,1],[1,2],[3,4]]

Output: 2

Hints (1)
  • Flood fill each unvisited node with DFS or BFS and count the floods.

Solutions

DFS flood fill. · Time O(V+E) · Space O(V+E)

func countComponents(n int, edges [][]int) int {
    adj := make([][]int, n)
    for _, e := range edges {
        adj[e[0]] = append(adj[e[0]], e[1])
        adj[e[1]] = append(adj[e[1]], e[0])
    }
    seen := make([]bool, n)
    count := 0
    for s := 0; s < n; s++ {
        if seen[s] {
            continue
        }
        count++
        stack := []int{s}
        for len(stack) > 0 {
            u := stack[len(stack)-1]
            stack = stack[:len(stack)-1]
            if seen[u] {
                continue
            }
            seen[u] = true
            for _, v := range adj[u] {
                if !seen[v] {
                    stack = append(stack, v)
                }
            }
        }
    }
    return count
}

Create a free account to submit solutions, track progress and save problems.

Create account