Medium
LABNumber of Connected Components in an Undirected Graph
Given n nodes and undirected edges, return the number of connected components.
EXAMPLES
Example 1
Input
{
"n": 5,
"edges": [
[
0,
1
],
[
1,
2
],
[
3,
4
]
]
}
Output
2FUNCTION SHAPE
n: intedges: intMatrix→intSOLUTION NOTE
This is actually a really important concept to know. Connected component is basically like an island.
Reveal reference solution +
pythonREFERENCE
def countComponents(self, n: int, edges: List[List[int]]) -> int:
adjList = defaultdict(list)
for u,v in edges:
adjList[u].append(v)
adjList[v].append(u)
visited = set()
ccs = []
def dfs(i, cc):
if i in visited: return
visited.add(i)
cc.append(i)
for nbr in adjList[i]:
dfs(nbr, cc)
for i in range(n):
if i in visited: continue
cc = []
dfs(i, cc)
ccs.append(cc)
return len(ccs)Time
O(n+m)Space
O(n+m)