Advertisement
Guest User

Untitled

a guest
Apr 21st, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. /////////BFS//////////
  2.  
  3. #include<bits/stdc++.h>
  4. #define max 10000
  5. using namespace std;
  6. vector<int> ara[max];
  7. bool visited[max];
  8. void bfs(int start)
  9. {
  10. queue<int>q;
  11. visited[start]=true;
  12. q.push(start);
  13. while(!q.empty())
  14. {
  15. int v=q.front();
  16. cout<<q.front()<<" ";
  17. q.pop();
  18. for(int i=0;i<ara[v].size();i++)
  19. {
  20. if(visited[ara[v][i]]==false)
  21. {
  22. q.push(ara[v][i]);
  23. visited[ara[v][i]]=true;
  24. }
  25. }
  26. }
  27. }
  28. int main()
  29. {
  30. int n,e,u,v,i,j;
  31. cin>>n>>e;
  32. while(e--)
  33. {
  34. cin>>u>>v;
  35. ara[u].push_back(v);
  36. }
  37. bfs(1);
  38. }
  39.  
  40.  
  41.  
  42. ///////////////////////DFS////////////////////
  43.  
  44. #include<bits/stdc++.h>
  45. using namespace std;
  46. #define max 100000
  47. vector<int>ara[max];
  48. bool visited[max];
  49. void dfs(int root)
  50. {
  51. stack<int>s;
  52. //visited[root]=true;
  53. s.push(root);
  54. int p;
  55. while (!s.empty())
  56. {
  57. p = s.top();
  58. s.pop();
  59. if (!visited[p])
  60. {
  61. cout << p << " ";
  62. visited[p] = true;
  63. }
  64. vector<int>::iterator i;
  65. for ( i = ara[p].begin(); i != ara[p].end(); ++i)
  66. if (!visited[*i])
  67. s.push(*i);
  68. }
  69. }
  70. int main()
  71. {
  72. int n,e,u,v,i,j;
  73. cin>>n>>e;
  74. while(e--)
  75. {
  76. cin>>u>>v;
  77. ara[u].push_back(v);
  78. }
  79. dfs(1);
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement