# Number of Provinces LeetCode Solution

Here, We see Number of Provinces LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

# List of all LeetCode Solution

## Problem Statement

There are `n` cities. Some of them are connected, while some are not. If city `a` is connected directly with city `b`, and city `b` is connected directly with city `c`, then city `a` is connected indirectly with city `c`.

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` matrix `isConnected` where `isConnected[i][j] = 1` if the `ith` city and the `jth` city are directly connected, and `isConnected[i][j] = 0` otherwise.

Return the total number of provinces.

Example 1:

Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2

Example 2:

Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3

## Number of Provinces LeetCode SolutionC++

``````class Solution {
public:
vis[node] = 1;
if(!vis[i]){
}
}
}
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
for(int i = 0;i<n;i++){
for(int j = 0;j<n;j++){
if(isConnected[i][j]){
}
}
}
vector<bool>vis(n,0);
int ans= 0;
for(int i = 0;i<n;i++){
if(!vis[i]){
ans++;
}
}
return ans;
}
};```Code language: JavaScript (javascript)```

## Number of Provinces LeetCode SolutionJava

``````class Solution {
public int findCircleNum(int[][] isConnected) {
int N = isConnected.length;
boolean[]visited = new boolean[N];
int count = 0;
for(int i = 0; i < N ;i++){
if(!visited[i]){
count++;
dfs(isConnected,i,visited);
}
}
return count;
}
private void dfs(int[][]isConnected,int i,boolean[]visited){
for(int j = 0 ; j < isConnected[i].length ; j++){
if(!visited[j] && isConnected[i][j] != 0){
visited[j] = true;
dfs(isConnected,j,visited);
}
}
}

}```Code language: PHP (php)```

## Number of Provinces SolutionJavaScript

``````var findCircleNum = function(isConnected) {
class UnionFind {
constructor(n) {
this.graph = [...Array(n)].map((_, i) => i);
this.groups = n;
}
find(id) {
if(this.graph[id] === id) return id;
this.graph[id] = this.find(this.graph[id]);
return this.graph[id];
}
union(x, y) {
const rootX = this.find(x);
const rootY = this.find(y);
if(rootX !== rootY) {
this.graph[rootY] = rootX;
this.groups--;
}
}
}
const N = isConnected.length, unionfind = new UnionFind(N);
for(let r = 0; r < N; r++) {
for(let c = 0; c < N; c++) {
if(isConnected[r][c]) unionfind.union(r, c);
}
}
return unionfind.groups;
};```Code language: JavaScript (javascript)```

## Number of Provinces SolutionPython

``````class Solution(object):
def findCircleNum(self, isConnected):
if not isConnected: return 0
s = len(isConnected)
seen = set()
def dfs(p):