<AI/>
enru
Все статьи

Number of provinces

LeetCode 547: Count groups of directly or indirectly connected cities using the Disjoint Set data structure.

Сложность
Средняя
Опубликовано
Темы
#graph#disjoint set
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

There are n cities, some of which are connected.

If city a is directly connected to city b, and city b is directly connected to city c, then cities a and c are connected indirectly.

A province is a group of directly or indirectly connected cities.

You are given an n x n matrix isConnected, where isConnected[i][j] = 1 if the i-th city and the j-th city are directly connected, and isConnected[i][j] = 0 otherwise.

Return the total number of provinces.

Constraints

  • The matrix size n is an integer in the range from 1 to 200
  • The matrix contains only 1 and 0
  • isConnected[i][j] == isConnected[j][i]

Examples

Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]

Answer: 2

Solution

There are quite a few solutions to this problem, and all of them are fairly involved. But it becomes easy if you know how the DisjointSet data structure (also known as UnionFind) works.

You can read about the implementation of DisjointSet in detail in this post.

Once we have the data structure implemented, the problem becomes very easy.

The algorithm:

  • Create an instance of DisjointSet.
  • Define a variable numberOfProvinces initially equal to n. We'll decrement it as we merge cities into provinces.
  • The main diagonal of isConnected represents each city's connection to itself, so we can skip it. We also don't need to check the whole matrix, since isConnected[i][j] == isConnected[j][i], so we only go over the elements above the main diagonal. For that, we run nested loops over i and j, starting from i = 0 and j = i + 1.
  • If two cities are connected (isConnected[i][j] == 1) and they are not in the same set yet, we merge cities i and j into one province with the union method and decrement numberOfProvinces.

After going over the matrix, numberOfProvinces holds the resulting number of provinces.

typescript
class DisjointSet {
  readonly nodes: number[];
 
  constructor(size: number) {
    this.nodes = new Array(size);
 
    for (let i = 0; i < size; i++) {
      this.nodes[i] = i;
    }
  }
 
  find(node: number): number {
    return this.nodes[node];
  }
 
  union(x: number, y: number): void {
    const rootX = this.find(x);
    const rootY = this.find(y);
 
    if (rootX !== rootY) {
      for (let i = 0; i < this.nodes.length; i++) {
        if (this.nodes[i] === rootY) {
          this.nodes[i] = rootX;
        }
      }
    }
  }
}
 
export const findCircleNum = (isConnected: number[][]): number => {
  const n = isConnected.length;
  const disjointSet = new DisjointSet(n);
 
  let numberOfProvinces = n;
 
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      if (isConnected[i][j] == 1 && disjointSet.find(i) != disjointSet.find(j)) {
        numberOfProvinces -= 1;
        disjointSet.union(i, j);
      }
    }
  }
 
  return numberOfProvinces;
};

Complexity Analysis

Time Complexity

  • Traversing the matrix takes O(n2)
  • A find call takes O(n)
  • A union call takes O(n)

The overall time complexity is O(n2).

Space Complexity

O(n) to store the state of the DisjointSet structure.