Leetcode 547. Number of Provinces
The problem “Number of Provinces” on LeetCode is defined as follows:
There are
n
cities. Some of them are connected, while some are not. If citya
is connected directly with cityb
, and cityb
is connected directly with cityc
, then citya
is connected indirectly with cityc
.A province is a group of directly or indirectly connected cities and no other cities outside of the group.
You are given an
n x n
matrixisConnected
whereisConnected[i][j] = 1
if the ith city and the jth city are directly connected, andisConnected[i][j] = 0
otherwise.Return the total number of provinces.
1 <= n <= 200
isConnected[i][i] = 1
for all i
meaning each city is connected to itself.isConnected[i][j] = isConnected[j][i]
indicating the undirected nature of the graph.We need to find the number of connected components in an undirected graph represented by the isConnected
matrix. Here’s a straightforward approach:
isConnected
matrix as an adjacency matrix to represent the graph.Here is the C++ code for the solution using DFS:
#include <vector>
using namespace std;
class Solution {
public:
void dfs(int city, vector<vector<int>>& isConnected, vector<bool>& visited) {
visited[city] = true;
for (int i = 0; i < isConnected.size(); ++i) {
if (isConnected[city][i] == 1 && !visited[i]) {
dfs(i, isConnected, visited);
}
}
}
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
vector<bool> visited(n, false);
int numberOfProvinces = 0;
for (int i = 0; i < n; ++i) {
if (!visited[i]) {
dfs(i, isConnected, visited);
numberOfProvinces++;
}
}
return numberOfProvinces;
}
};
visited
array and recursive call stack in the worst case.This solution ensures we efficiently determine the number of provinces in the given graph representation.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?