323 Number of Connected Components in an Undirected Graph

1. Question

Givennnodes labeled from0ton - 1and 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.

Example 1:

     0          3
     |          |
     1 --- 2    4

Givenn = 5andedges = [[0, 1], [1, 2], [3, 4]], return2.

Example 2:

     0           4
     |           |
     1 --- 2 --- 3

Givenn = 5andedges = [[0, 1], [1, 2], [2, 3], [3, 4]], return1.

Note: You can assume that no duplicate edges will appear inedges. Since all edges are undirected,[0, 1]is the same as[1, 0]and thus will not appear together inedges.

2. Implementation

(1) BFS

(2) DFS

(3) Union Find

3. Time & Space Complexity

BFS: 时间复杂度O(n),空间复杂度O(n)

DFS: 时间复杂度O(n),空间复杂度O(n)

Union Find: 时间复杂度O(n), 空间复杂度O(n)

Last updated

Was this helpful?