HmHimu

dfs

Jul 20th, 2017
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3. int adj[100][100],v;
  4. int color[100],time,prev[100],d[100],f[100];
  5. void DFS_Visit(int u);
  6. void DFS(int s)
  7. {
  8.  
  9. for(int i=1;i<=v;i++)
  10. {
  11. color[i]=0;
  12. prev[i]=-1;
  13. d[i]=-1;
  14. f[i]=-1;
  15. }
  16. time=0;
  17. for(int i=1;i<=v;i++)
  18. {
  19. if(color[i]==0)
  20. DFS_Visit(i);
  21. }
  22. }
  23. void DFS_Visit(int u)
  24. {
  25. color[u]=1;
  26. time++;
  27. d[u]=time;
  28. for(int i=1;i<=v;i++)
  29. {
  30. int k=adj[u][i];
  31. if(k==1&&color[i]==0)
  32. {
  33. prev[i]=u;
  34. DFS_Visit(i);
  35. }
  36. }
  37. color[u]=2;
  38. time++;
  39. f[u]=time;
  40. }
  41. void DFS_Display()
  42. {
  43. cout<<"veretex :";
  44. for(int i=1;i<=v;i++)
  45. {
  46. cout<<i<<" ";
  47. }
  48. cout<<endl;
  49. cout<<"Colour :";
  50. for(int i=1;i<=v;i++)
  51. {
  52. cout<<color[i]<<" ";
  53. }
  54. cout<<endl;
  55. cout<<"Discovering :";
  56. for(int i=1;i<=v;i++)
  57. {
  58. cout<<d[i]<<" ";
  59. }
  60. cout<<endl;
  61. cout<<"Finishing :";
  62. for(int i=1;i<=v;i++)
  63. {
  64. cout<<f[i]<<" ";
  65. }
  66. cout<<endl;
  67. cout<<"Prev :";
  68. for(int i=1;i<=v;i++)
  69. {
  70. cout<<prev[i]<<" ";
  71. }
  72. cout<<endl;
  73. }
  74. int main()
  75. {
  76. int a,b,i,j,k,s;
  77. cout<<"Input Vertex Number :";
  78. cin>>v;
  79. k=1;
  80. do
  81. {
  82. cout<<"Edge "<<k<<" : ";
  83. cin>>a>>b;
  84. if(a<=0 || b<=0 || a>v || b>v)
  85. {
  86. cout<<"Invalid Input,try again... "<<endl;
  87. }
  88. else
  89. {
  90. adj[a][b]=1;
  91. k++;
  92. }
  93. }while(a!=0 && b!=0);
  94. for(i=1;i<=v;i++)
  95. {
  96. for(j=1;j<=v;j++)
  97. {
  98. cout<<adj[i][j]<<" ";
  99. }
  100. cout<<endl;
  101. }
  102. cout<<"Source vertex :";
  103. cin>>s;
  104. DFS(s);
  105. DFS_Display();
  106. }
Add Comment
Please, Sign In to add comment