Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /////////BFS//////////
- #include<bits/stdc++.h>
- #define max 10000
- using namespace std;
- vector<int> ara[max];
- bool visited[max];
- void bfs(int start)
- {
- queue<int>q;
- visited[start]=true;
- q.push(start);
- while(!q.empty())
- {
- int v=q.front();
- cout<<q.front()<<" ";
- q.pop();
- for(int i=0;i<ara[v].size();i++)
- {
- if(visited[ara[v][i]]==false)
- {
- q.push(ara[v][i]);
- visited[ara[v][i]]=true;
- }
- }
- }
- }
- int main()
- {
- int n,e,u,v,i,j;
- cin>>n>>e;
- while(e--)
- {
- cin>>u>>v;
- ara[u].push_back(v);
- }
- bfs(1);
- }
- ///////////////////////DFS////////////////////
- #include<bits/stdc++.h>
- using namespace std;
- #define max 100000
- vector<int>ara[max];
- bool visited[max];
- void dfs(int root)
- {
- stack<int>s;
- //visited[root]=true;
- s.push(root);
- int p;
- while (!s.empty())
- {
- p = s.top();
- s.pop();
- if (!visited[p])
- {
- cout << p << " ";
- visited[p] = true;
- }
- vector<int>::iterator i;
- for ( i = ara[p].begin(); i != ara[p].end(); ++i)
- if (!visited[*i])
- s.push(*i);
- }
- }
- int main()
- {
- int n,e,u,v,i,j;
- cin>>n>>e;
- while(e--)
- {
- cin>>u>>v;
- ara[u].push_back(v);
- }
- dfs(1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement