Tap here to switch tabs
Problem
Ask
Submissions

Problem: Number of Provinces

med
30 min
Explore how to determine the number of provinces from a matrix representing city connections. Learn to apply graph traversal methods to identify groups of directly or indirectly connected cities and solve graph connectivity challenges efficiently.

Statement

Given nn cities, some are directly connected, and others are not. You are given an n×nn \times n matrix called cities, where cities[i][j] =1= 1 means city ithi^{th} and city jthj^{th} are directly connected, and cities[i][j] =0= 0 means they are not directly connected.

Note: If city AA is directly connected to city BB and city BB is directly connected to city CC, then city AA is indirectly connected to city CC.

The task is to return the total number of groups of connected cities directly or indirectly. These groups are referred to as provincesA province is a group of directly or indirectly connected cities with no other cities outside of the group..

Constraints:

  • 11\leq nn 200\leq200

  • n==n == cities.length

  • n==n == cities[i].length, where 00\leq ii n\leq n

  • cities[i][j] is either 00 or 11.

  • cities[i][i] ==1== 1

  • cities[i][j] ==== cities[j][i]

Tap here to switch tabs
Problem
Ask
Submissions

Problem: Number of Provinces

med
30 min
Explore how to determine the number of provinces from a matrix representing city connections. Learn to apply graph traversal methods to identify groups of directly or indirectly connected cities and solve graph connectivity challenges efficiently.

Statement

Given nn cities, some are directly connected, and others are not. You are given an n×nn \times n matrix called cities, where cities[i][j] =1= 1 means city ithi^{th} and city jthj^{th} are directly connected, and cities[i][j] =0= 0 means they are not directly connected.

Note: If city AA is directly connected to city BB and city BB is directly connected to city CC, then city AA is indirectly connected to city CC.

The task is to return the total number of groups of connected cities directly or indirectly. These groups are referred to as provincesA province is a group of directly or indirectly connected cities with no other cities outside of the group..

Constraints:

  • 11\leq nn 200\leq200

  • n==n == cities.length

  • n==n == cities[i].length, where 00\leq ii n\leq n

  • cities[i][j] is either 00 or 11.

  • cities[i][i] ==1== 1

  • cities[i][j] ==== cities[j][i]