AlgoMaster Logo

Number of Provinces

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Depth-First Search (DFS)

Intuition:

The problem can be conceptualized as finding connected components in an undirected graph. Each city is a node, and a direct road between two cities is an edge. Using Depth-First Search, we can explore all nodes (i.e., cities) connected to a starting node, marking them as visited. Each new unvisited node indicates the start of a new province.

Code:

2. Breadth-First Search (BFS)

Intuition:

Similar to the DFS approach, we aim to find connected components. However, BFS uses a queue to explore all nodes extensively level by level. Whenever we find a new city that hasn't been visited, we add it to the queue and mark it as part of the same province.

Code:

3. Union-Find

Intuition:

Union-Find efficiently tracks and merges disjoint sets, or connected components, which suits this problem perfectly. Initially, each city is its own province. As we process direct roads between cities, we union their sets. The number of unique roots in the Union-Find structure at the end will give us the number of provinces.

Code: