Advertisement
HmHimu

bfs(alg)adjecency mat

May 25th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. #include<Queue>
  4. using namespace std;
  5.  
  6.  
  7.  
  8.  
  9. int v,i,j,a,b,k=1,s;
  10. int p[100],d[2000000],clr[100];
  11. int adj[100][100],u;
  12.  
  13.  
  14. void BFS(int s)
  15. {
  16.  
  17.  
  18. for(i=1;i<=v;i++)
  19. {
  20. clr[i]=0;
  21. p[i]=-1;
  22. d[i]=0;
  23. }
  24.  
  25.  
  26.  
  27. clr[s]=1;
  28. //p[s]=-1;
  29. queue<int> Q;
  30.  
  31. Q.push(s);
  32.  
  33. while(!Q.empty()){
  34.  
  35. u=Q.front();
  36. Q.pop();
  37.  
  38. for(i=1;i<=v;i++)
  39. {
  40. if(adj[u][i]==1 && clr[i]==0)
  41. {
  42. clr[i]=1;
  43. d[i]=d[u]+1;
  44. p[i]=u;
  45. Q.push(i);
  46. }
  47. }
  48. clr[u]=2;
  49. }
  50.  
  51. cout<<"previous"<<endl;
  52. for(i=1;i<=v;i++)
  53. {
  54. cout<<p[i]<<" ";
  55. }
  56. cout<<endl;
  57.  
  58. cout<<"cost"<<endl;
  59. for(i=1;i<=v;i++)
  60. {
  61. cout<<d[i]<<" ";
  62. }
  63. cout<<endl;
  64.  
  65. cout<<"color"<<endl;
  66. for(i=1;i<=v;i++)
  67. {
  68. cout<<clr[i]<<" ";
  69. }
  70.  
  71.  
  72.  
  73.  
  74.  
  75. }
  76.  
  77.  
  78. int main()
  79. {
  80.  
  81.  
  82. cout<<"vertex: ";
  83. cin>>v;
  84.  
  85. do{
  86.  
  87. cout<<"Edge"<<k<<":";
  88. cin>> a >> b ;
  89. cout<<endl;
  90.  
  91. if(a>v+1 || b>v+1)
  92. {
  93. cout<<"Input is invalid"<<endl;
  94.  
  95. }
  96. else{
  97.  
  98. adj[a][b]=1;
  99.  
  100. adj[b][a]=1;
  101.  
  102.  
  103.  
  104. }
  105. k++;
  106.  
  107. }while(a!=0 && b!=0);
  108.  
  109.  
  110.  
  111.  
  112. for(i=1;i<=v;i++){
  113.  
  114. int count=0;
  115. for(j=1;j<=v;j++)
  116. {
  117.  
  118. cout<<adj[i][j]<<" ";
  119.  
  120.  
  121.  
  122. }
  123. cout<<endl;
  124. }
  125.  
  126. cout<<"Enter source node"<<endl;
  127. cin>>s;
  128. if(s>v || s< 1)
  129. cout<<"invalid input"<<endl;
  130. else
  131. BFS(s);
  132.  
  133.  
  134. return 0;
  135.  
  136. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement