Skip to main content

Command Palette

Search for a command to run...

Graph - Find the Number of Provinces

Published
1 min read
Graph - Find the Number of Provinces
N

I am Nirbhay Singh , I am starting this blog to document my coding journey of becoming a software developer and to get my first $ 100k offer .

Find the Number of Provinces

  1. https://www.codingninjas.com/studio/problems/find-the-number-of-states_1377943?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf

  2. https://leetcode.com/problems/number-of-provinces/description/

Hint Video:

Code:

void bfs(vector<int> adjLs[], 
    vector<int>& visited, int start){

    visited[start] = 1;

    queue<int> q;
    q.push(start);

    while(!q.empty()){
        int node = q.front();
        q.pop();

        for(auto &it: adjLs[node]){
            if(!visited[it]){
                visited[it] = 1;
                q.push(it);
            }
        }
    }

    return;

}

int findNumOfProvinces(vector<vector<int>>& roads, int n) {
    // Write your code here.

    vector<int> adjLs[n];

    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            if(roads[i][j]==1 && i!=j){
                adjLs[i].push_back(j);
                adjLs[j].push_back(i);
            }
        }   
    }

    vector<int> vis(n,0);

    int count = 0;

    for(int i=0;i<n;i++){
        if(!vis[i]){
            bfs(adjLs,vis,i);
            count++;
        }
    }

    return count;
}

DSA prep

Part 5 of 22

This series is specifically to document and share my learning of Data Structure and Algorithms and building the programmers intuition to solve a problem through coding and getting my first job as SDE.

Up next

Boundary Traversal of Binary Tree

Boundary Traversal of Binary Tree Problem Link: https://www.codingninjas.com/studio/problems/boundary-traversal-of-binary-tree_790725?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf https://leetcode.com/problems/boundary-of-binary-t...

More from this blog

Daily Code by Nirbhay

74 posts

Hey, this is Nirbhay. I started this blog to document my journey of learning to code and get my first $100k offer. I'll be sharing the things related to DSA, backend development, devops and many more.