BFS in Graph

PHOTO EMBED

Fri Mar 17 2023 14:11:38 GMT+0000 (Coordinated Universal Time)

Saved by @Ranjan_kumar #c++

#include <bits/stdc++.h> 

void makeAdj(unordered_map<int, set<int>>&mp1, vector<pair<int, int>> &edges)
{
    for(int i=0; i<edges.size(); i++)
    {
        int u = edges[i].first;
        int v = edges[i].second;
        mp1[u].insert(v);
        mp1[v].insert(u);
    }
}

void bfstrav(vector<int> &ans, unordered_map<int, bool> &visited, unordered_map<int, set<int>>&mp1, int node)
{
    queue<int> q;
    q.push(node);
    visited[node]=1;

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

        ans.push_back(p);

        for(auto x: mp1[p])
        {
            if(!visited[x]) 
            {
                q.push(x);
                visited[x]=1;
            }
        }

    }
}


vector<int> BFS(int vertex,vector<pair<int, int>> edges)
{
    vector<int> ans;
    unordered_map<int, bool> visited;
    unordered_map<int, set<int>>mp1;
    makeAdj(mp1, edges);
    for(int i=0;i<vertex;i++)
    {
        if(!visited[i]) bfstrav(ans, visited, mp1, i);
    }
    return ans;
    // Write your code here
}
content_copyCOPY

https://www.codingninjas.com/codestudio/problems/bfs-in-graph_973002