Created
August 18, 2020 09:59
-
-
Save pathakcodes/568662d894f3d64ce7bb41bba26a4cf4 to your computer and use it in GitHub Desktop.
Graph Implemetation and DFS and BFS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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