Advertisement
Rakibul_Ahasan

BFS_Implementation

Nov 11th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define WHITE 1
  5. #define GRAY 2
  6. #define BLACK 3
  7.  
  8. int adj[100][100];
  9. int node,edge;
  10. int color[100];
  11.  
  12. int parent[100];
  13. int dis[100];
  14.  
  15. void dfs(int x){
  16.     for(int i=0;i<node;i++){
  17.         color[i]=WHITE;
  18.         dis[i]=INT_MIN;
  19.         parent[i]=-1;
  20.     }
  21.  
  22.     dis[x]=0;
  23.     parent[x]=-1;
  24.  
  25.     queue<int>q;
  26.     q.push(x);
  27.  
  28.     while(!q.empty()){
  29.         int z;
  30.         z=q.front();
  31.         q.pop();
  32.         color[z]=GRAY;
  33.  
  34.         cout<<z<<" ";
  35.  
  36.         for(int i=0;i<node;i++){
  37.           if(adj[z][i]==1){
  38.            if(color[i]==WHITE){
  39.                dis[i]=dis[z]+1;
  40.                 parent[i]=z;
  41.                q.push(i);
  42.            }
  43.         }
  44.     }
  45.         color[z]=BLACK;
  46.  }
  47. }
  48.  
  49. int main()
  50. {
  51.     freopen("input.txt","r",stdin);
  52.     cin>>node>>edge;
  53.  
  54.     int n1,n2;
  55.     for(int i=0;i<edge;i++){
  56.          cin>>n1>>n2;
  57.         adj[n1][n2]=1;
  58.         adj[n2][n1]=1;
  59.     }
  60.     dfs(0);
  61.     cout<<"\n"<<parent[5]<<endl;
  62.     cout<<dis[6]<<endl;
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement