There are n cities, numbered 0 to n - 1. You get an n x n matrix isConnected: isConnected[i][j] is 1 when a road runs directly between city i and city j, and 0 when it doesn't. Roads go both ways, so the matrix is symmetric, and every city counts as linked to itself.
Two cities belong together when you can drive from one to the other, either on a direct road or through other cities on the way. A province is a group of cities that all belong together, with no city outside the group linked to any city inside it.
Return the number of provinces.
Cities 0 and 2 share a road, and so form one province. Cities 1, 3 and 4 form the other: 1 and 4 have no road between them, but both have one to 3.
The roads form a single chain, so every city can reach every other one. That makes one province.
No roads at all: each city is a province by itself.
Constraints
1 <= n <= 200isConnected.length == n and isConnected[i].length == nisConnected[i][j] is 0 or 1.isConnected[i][i] == 1isConnected[i][j] == isConnected[j][i]Read the matrix as a graph: each city is a node and each 1 off the diagonal is an edge. A province is then one connected piece of that graph, so the question is how many pieces there are.
Draw the matrix as a graph. Each city is a dot, and each 1 off the diagonal is a line between two dots. A province is then one piece of that drawing: a set of dots joined to each other by lines, with no line leaving the set. The answer is how many separate pieces there are.
Time O(n²)Space O(n)
The full walkthrough and code are part of Premium
2