Graph Theory-Revision
547. Number of Provinces
In this question, the connected nodes are represented in the form of an Adjacency Matrix, so, first of all, we have to make an adjacency list.
Once the adjacency list is created then we can count the number of provinces by simply dfs traversal of the adjacency list and can easily count the number of Provinces(cnt).
void dfs(int node,vector<int>& vis,vector<int> adj[])
{
vis[node]=1;
for(auto it:adj[node])
{
if(!vis[it])
{
dfs(it,vis,adj);
}
}
}
int findCircleNum(vector<vector<int>>& isConnected)
{
int cnt=0;
int n = isConnected.size();
vector <int> adj[n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j && isConnected[i][j]==1)
{
adj[i].push_back(j);
}
}
}
vector<int> vis(n,0);
for(int i = 0; i < n; i++)
{
if(!vis[i])
{
cnt++;
dfs(i,vis,adj);
}
}
return cnt;
}