Number of Provinces


Link: Number of Provinces


Problem Statement

Given an n x n matrix isConnected, where isConnected[i][j] = 1 indicates that the i-th and j-th cities are directly connected, and 0 otherwise, a province is a group of directly or indirectly connected cities, with no external connections.

Return the total number of provinces.


Examples

Example 1

Input:

isConnected = [
  [1,1,0],
  [1,1,0],
  [0,0,1]
]

Output: 2

Explanation:


Example 2

Input:

isConnected = [
  [1,0,0],
  [0,1,0],
  [0,0,1]
]

Output: 3

Each city is isolated, forming its own province.


Constraints


Intuition

This is a connected components in a graph problem.

We're being asked to count the number of connected components in the graph — each one is a province.

Approaches:


Key Idea

  1. Maintain a visited[] array.

  2. Iterate through all nodes. If a node hasn't been visited:

    • Run DFS from that node.

    • Increment the province count.

  3. Each DFS traversal marks all cities in a single province.

Java Code

class Solution {
    public int findCircleNum(int[][] isConnected) {
        int n = isConnected.length;
        boolean[] visited = new boolean[n];
        int provinceCount = 0;

        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                dfs(isConnected, visited, i);
                provinceCount++;
            }
        }

        return provinceCount;
    }

    private void dfs(int[][] graph, boolean[] visited, int node) {
        visited[node] = true;
        for (int j = 0; j < graph.length; j++) {
            if (graph[node][j] == 1 && !visited[j]) {
                dfs(graph, visited, j);
            }
        }
    }
}

Dry Run

Input:

isConnected = [
  [1,1,0],
  [1,1,0],
  [0,0,1]
]

Step-by-step:

Final Output: 2


Time & Space Complexity

Metric Value
Time Complexity O(n²) → Traversing the matrix
Space Complexity O(n) → visited[] array
Recursion Stack Space O(n) → in worst-case DFS

Key Idea

Java Code

class Solution {
    public int findCircleNum(int[][] isConnected) {
        int n = isConnected.length;
        boolean[] visited = new boolean[n];
        int provinces = 0;

        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                Queue<Integer> queue = new LinkedList<>();
                queue.offer(i);

                while (!queue.isEmpty()) {
                    int current = queue.poll();
                    visited[current] = true;

                    for (int j = 0; j < n; j++) {
                        if (isConnected[current][j] == 1 && !visited[j]) {
                            queue.offer(j);
                        }
                    }
                }

                provinces++;
            }
        }

        return provinces;
    }
}

Time & Space Complexity (BFS)

Metric Value
Time Complexity O(n²)
Space Complexity O(n) → visited[] + queue

Applications