#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 }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter