Number of provinces

Graphs Traversal Problems Medium
  • Fun Fact: The concept derived from this problem, is often used in the domain of social networking applications like LinkedIn, Facebook etc
  • They use a similar concept in identifying 'network clusters' in their friend graph
  • A network cluster, in this case, could be seen as a 'province' where everyone is somehow connected
  • This helps in refining their recommendation systems to suggest new connections within the same network cluster and essentially grow the regional network
  • Algorithms with a similar foundation to this are also used in the detection of communities in various network structures

Given an undirected graph with V vertices. Two vertices u and v belong to a single province if there is a path from u to v or v to u. Find the number of provinces. The graph is given as an n x n matrix adj where adj[i][j] = 1 if the ith city and the jth city are directly connected, and adj[i][j] = 0 otherwise.


A province is a group of directly or indirectly connected cities and no other cities outside of the group.

Examples:

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

Output: 2

Explanation:In this graph, there are two provinces: [1, 4] and [2, 3]. City 1 and city 4 have a path between them, and city 2 and city 3 also have a path between them. There is no path between any city in province 1 and any city in province 2.

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

Output: 2

Explanation: The graph clearly has 2 Provinces [1,3] and [2]. As city 1 and city 3 has a path between them they belong to a single province. City 2 has no path to city 1 or city 3 hence it belongs to another province.

Input: adj= [ [1, 1], [1, 1] ]

Constraints

  •   1 <= V <= 300
  •   V == adj.length
  •   V == adj[i].length
  •   adj[i][j] is 1 or 0.
  •   adj[i][i] == 1
  •   a[i][j] == adj[j][i]

Hints

  • Treat each row of the adjacency matrix as a node and use DFS or BFS to explore all connected nodes starting from an unvisited city. Every time a new DFS/BFS starts, it identifies a new province (connected component).
  • Maintain a boolean array visited[V] to track which cities have been explored. Every DFS/BFS call finds one province, so increment the province count.

Company Tags

Rockstar Games GE Healthcare PayPal Zoho Western Digital Bungie Salesforce Oracle Activision Blizzard Boston Consulting Group Optum Square Shopify HashiCorp ARM Uber American Express Zynga Target Instacart McKinsey & Company Ernst & Young Texas Instruments Etsy Riot Games Google Microsoft Amazon Meta Apple Netflix Adobe