Skip to content

Instantly share code, notes, and snippets.

@pathakcodes
Created August 18, 2020 09:59
Show Gist options
  • Save pathakcodes/568662d894f3d64ce7bb41bba26a4cf4 to your computer and use it in GitHub Desktop.
Save pathakcodes/568662d894f3d64ce7bb41bba26a4cf4 to your computer and use it in GitHub Desktop.
Graph Implemetation and DFS and BFS
/**
coded by - pathakcodes //revamped
**/
#include<bits/stdc++.h>
using namespace std ;
map<int, vector<int>> graph ;
map<int, bool> visited ;
map<int, int> level ;
void dfs(int s){
cout << s << endl;
visited[s] = true ;
for(auto list : graph[s]){
if(visited[list] == false)
dfs(list);
}
}
void bfs(int s ){
queue<int> q ;
q.push(s);
level[s] = 0 ;
int prevLevel = 0, curLevel = 0 ;
while(!q.empty()){
int top = q.front() ;
visited[top] = true ;
q.pop();
for(auto list:graph[top]){
if(visited[list] == false){
level[list] = level[top]+1;
q.push(list);
}
}
curLevel = level[top] ;
if(prevLevel != curLevel){
cout << endl ;
prevLevel = curLevel ;
}
cout << top << " " ;
}
}
int main(){
int n ;
cin >> n ;
for(int i = 0 ; i < n ; i++){
int start, end ;
cin >> start >> end ;
graph[start].push_back(end);
graph[end].push_back(start);
}
// dfs(1) ;
bfs(1) ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment