Skip to content
BytePatterns

Count Provinces

MediumUnion-Find#union-find#connected-components~25m

Problem

A square matrix records which cities are directly linked: matrix[i][j] is 1 when city i and city j are joined, and 0 otherwise. The matrix is symmetric and every city is linked to itself. A province is a group of cities reachable from one another, directly or through others. Return how many provinces there are.

Examples

Input:  matrix = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]
Output: 2
Why:    cities 0 and 1 are joined; city 2 stands alone
Input:  matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
Output: 3
Why:    nothing is linked, so every city is its own province
Input:  matrix = [[1]]
Output: 1
Why:    edge case, a single city is one province

Hints

0 / 3

Stuck on the idea rather than the code? Disjoint Sets Basics covers it.