Leetcode 547: Number of Provinces

grid47
grid47
Exploring patterns and algorithms
Sep 13, 2024 5 min read

A map of regions where provinces are counted and highlighted, each province glowing softly.
Solution to LeetCode 547: Number of Provinces Problem

You are given a matrix where each element indicates if two cities are directly connected. Your task is to determine the number of provinces formed by the cities. A province is a group of directly or indirectly connected cities.
Problem
Approach
Steps
Complexity
Input: The input is an n x n matrix 'isConnected' where 'isConnected[i][j]' is 1 if city 'i' is connected directly to city 'j', and 0 otherwise.
Example: Input: isConnected = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]
Constraints:
• 1 <= n <= 200
• n == isConnected.length
• n == isConnected[i].length
• isConnected[i][j] is 1 or 0.
• isConnected[i][i] == 1
• isConnected[i][j] == isConnected[j][i]
Output: Return the total number of provinces in the network of cities.
Example: Output: 2
Constraints:
• The output is an integer representing the total number of provinces.
Goal: The goal is to compute the number of provinces by grouping cities that are connected directly or indirectly.
Steps:
• Use a depth-first search (DFS) or union-find approach to group cities that are directly or indirectly connected.
• Track the groups of cities and count how many separate groups (provinces) there are.
Goal: The matrix will contain only 1s and 0s, with the diagonal always being 1 to indicate each city is connected to itself.
Steps:
• The matrix will have dimensions n x n, where 1 <= n <= 200.
Assumptions:
• The input matrix is always valid and satisfies the given constraints.
Input: Input: isConnected = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]
Explanation: In this example, there are two provinces: one consisting of city 1 and city 2, and the second consisting only of city 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus