Advertisement
shabbyheart

BFS by color

Dec 6th, 2019
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. queue<int>q;
  4. string color[10000]="white";
  5. int d[100000],p[100000];
  6. class Node{
  7. public:
  8.     int destination;
  9.     int weight;
  10.     Node *next;
  11. };
  12. class Integer{
  13. public:
  14.     Node *head = NULL;
  15. };
  16.  
  17. void addEdge(Integer arr[],int sorc,int dest)
  18. {
  19.     Node *newNode = new Node();
  20.     newNode->destination = dest;
  21.     newNode->next = NULL;
  22.     if( arr[sorc].head == NULL)
  23.         arr[sorc].head = newNode;
  24.     else
  25.     {
  26.         Node *temp = arr[sorc].head;
  27.         while(temp->next != NULL)
  28.             temp = temp->next;
  29.         temp->next = newNode;
  30.     }
  31. }
  32. void bfs(Integer arr[],int s)
  33. {
  34.     q.push(s);
  35.     color[s] = "Gray";
  36.     d[s] = 0;
  37.     p[s] = 0;
  38.     while( !q.empty())
  39.     {
  40.         int parent = q.front();
  41.         q.pop();
  42.         cout<<parent<<" ";
  43.         Node *temp = arr[parent].head;
  44.         while( temp!=NULL)
  45.         {
  46.             if( color[temp->destination] == "white")
  47.             {
  48.                 q.push(temp->destination);
  49.                 color[temp->destination] = "Gray";
  50.                 d[temp->destination] = d[parent] + 1;
  51.                 p[temp->destination] = parent;
  52.  
  53.             }
  54.             temp = temp->next;
  55.         }
  56.         color[parent] = "Black";
  57.     }
  58. }
  59. //void display(Integer listt[], int v)
  60. //{
  61. //    for(int i =0; i<=v; i++)
  62. //    {
  63. //        cout<<"\n Adjacency list of vertex "<<i<<" -->";
  64. //        while(listt[i].head != NULL)
  65. //        {
  66. //            cout<<" "<<listt[i].head->destination;
  67. //            listt[i].head = listt[i].head->next;
  68. //        }
  69. //    }
  70. //
  71. //}
  72. int main()
  73. {
  74.     freopen("input.txt","r",stdin);
  75.     int v;
  76.     cin>>v;
  77.     Integer arr[v];
  78.  
  79.     /// eita na korle arr er vitore v+1 dite hobe
  80.      for (int i = 0; i <= v; i++)
  81.         arr[i].head = NULL;
  82.  
  83.     /// getting input
  84.     int m,n;
  85.     while(scanf("%d%d",&m,&n) == 2)
  86.     {
  87.         addEdge(arr,m,n);
  88.         addEdge(arr,n,m);
  89.     }
  90.     ///display(arr,v);
  91.     bfs(arr,1);
  92.  
  93.     cout<<endl<<p[6];
  94.  
  95.  
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement