Count Connected Components (Adjacency Matrix)

graphs · function

Description

Given an N x N adjacency matrix `m` for an undirected graph, return the
number of connected components (distinct subgraphs).

m[i][j] == 1 means there is an edge between nodes i and j.
m[i][i] is always 1 (a node is connected to itself).
The matrix is symmetric: m[i][j] == m[j][i].

Example:
    m = [[1, 1, 0],
         [1, 1, 0],
         [0, 0, 1]]
    -> 2 components: {0, 1} and {2}

The drill: for each unvisited node, run a fill (DFS or BFS) that walks
row m[node] to find neighbors, marks them visited, and recurses. Each
fill-launch increments the component count.

Constraints

- 1 <= N <= 200
- m[i][j] is 0 or 1
- m[i][i] == 1
- m is symmetric (undirected edges)
solution.py
output
Run the cases to see results here.