Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std ;
- vector<int> g[100010] ;
- bool vis[100010] ;
- void dfs(int x) {
- cout << x << ' ' ;
- vis[x] = true ;
- for(auto i:g[x])
- if(!vis[i])
- dfs(i) ;
- }
- void bfs() {
- queue<int> qu ;
- vis[1] = true ;
- qu.push(1) ;
- while(!qu.empty()) {
- int u = qu.front() ;
- qu.pop() ;
- cout << u << ' ' ;
- for(auto i:g[u]) {
- if(!vis[i]) {
- vis[i] = true ;
- qu.push(i) ;
- }
- }
- }
- }
- int main() {
- int n, m ;
- cin >> n >> m ;
- for (int i=0; i<m; ++i) {
- int a, b ;
- cin >> a >> b ;
- g[a].push_back(b) ;
- g[b].push_back(a) ;
- }
- for (int i=1; i<=n; ++i) vis[i] = false ;
- dfs(1) ;
- cout << endl ;
- for (int i=1; i<=n; ++i) vis[i] = false ;
- bfs() ;
- cout << endl ;
- }
- /*
- 5 6
- 1 2
- 1 4
- 2 3
- 2 4
- 2 5
- 4 5
- */
Advertisement
Add Comment
Please, Sign In to add comment