VasilM

bfs shortest path

Apr 2nd, 2014
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. const int MAXN = 1000;
  5. int used[MAXN+1], Q[MAXN], P[MAXN], G[MAXN][MAXN], N, b, e;
  6.  
  7. void make_empty(){
  8.     b=0;
  9.     e=-1;
  10. }
  11.  
  12. void push(int x){
  13.     Q[++e]=x;
  14. }
  15.  
  16. int pop(){
  17.     return Q[b++];
  18. }
  19.  
  20. bool emptyQ(){
  21.     return b>e;
  22. }
  23.  
  24. void BFS(int r){
  25.   int  x,y,i;
  26.  
  27.   for(i=1;i<=N;i++) used[i]=0;
  28.   make_empty();
  29.   push(r);
  30.   used[r]=1;
  31.   P[r]=0;
  32.  
  33.   while(!emptyQ()){
  34.     x=pop();
  35.     for(i=1;i<=G[x][0];i++){
  36.       y=G[x][i];
  37.       if(!used[y]){
  38.         push(y);
  39.         used[y]=1;
  40.         P[y]=x;
  41.         cout<< y <<" ";
  42.       }
  43.     }
  44.   }
  45. }
  46.  
  47.  
  48. int main(){
  49.  
  50.     setlocale(0,"");
  51.     int n,x,y, startV,endW, current, pathLen = 1;
  52.  
  53.      cin >> n;
  54.  
  55.         for( int i=0; i<n; i++ ){
  56.             cin >> y >> x;
  57.             G[x][++G[x][0]] = y;
  58.             G[y][++G[y][0]] = x;
  59.         }
  60.  
  61.     cin >> endW;
  62.     cin >> startV;
  63.     BFS(endW);
  64.     current = startV;
  65.     while( P[current] != endW ) {
  66.            current = P[current];
  67.            pathLen++;
  68.            }
  69.    
  70.     cout << "Shortest path: " << pathLen << "\n";
  71.  
  72.     return 0;
  73. }
  74. /*
  75. 17
  76. 1 7
  77. 1 9
  78. 1 2
  79. 2 4
  80. 2 6
  81. 6 7
  82. 6 10
  83. 6 5
  84. 7 3
  85. 3 10
  86. 10 11
  87. 5 11
  88. 8 11
  89. 5 10
  90. 9 10
  91. 4 5
  92. 4 8
  93. 1 11
  94. */
Advertisement
Add Comment
Please, Sign In to add comment