Problem Description
Given an n x n matrix isConnected where isConnected[i][j] = 1 means city i is directly connected to city j (and 0 otherwise), find the total number of provinces. A province is a group of directly or indirectly connected cities.
Key Insights
- The matrix represents an undirected graph where each node is a city.
- Direct and indirect connections imply finding connected components in the graph.
- DFS, BFS, or Union-Find can be used to traverse and count connected components.
- Each traversal starting from an unvisited city represents a new province.
Space and Time Complexity
Time Complexity: O(n^2) – Every cell of the matrix is inspected. Space Complexity: O(n) – For the visited array (and recursion stack in DFS worst-case).
Solution
To solve the problem, we use a Depth-First Search (DFS) approach. Start by iterating over each city. When encountering an unvisited city, initiate a DFS to mark all cities within the same province as visited. Increment the province counter for each DFS initiation. This effectively counts the number of connected components (provinces) in the graph.
Code Solutions
Python:
JavaScript:
C++:
Java: