Advertisement
Guest User

Untitled

a guest
Dec 8th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.29 KB | None | 0 0
  1. void bfs(Graph *graph, Node *s, Operation *op)
  2. {
  3.     // TOOD: implement the BFS algorithm on the graph, starting from the node s
  4.     // at the end of the algorithm, every node reachable from s should have the color BLACK
  5.     // for all the visited nodes, the minimum distance from s (dist) and the parent in the BFS tree should be set
  6.     // for counting the number of operations, the optional op parameter is received
  7.     // since op can be NULL (when we are calling the bfs for display purposes), you should check it before counting:
  8.     // if(op != NULL) op->count();
  9.  
  10.     int poz = 0;
  11.     for (int w = 0; w < graph->nrNodes; w++) {
  12.         if (graph->v[w] == s) {
  13.             graph->v[w]->color = 1;
  14.             break;
  15.         }
  16.     }
  17.  
  18.     list<Node*> coada;
  19.     coada.push_back(s);
  20.  
  21.     while (!coada.empty()) {
  22.         Node* u = coada.front();
  23.         coada.pop_front();
  24.  
  25.         for (int w = 0; w < u->adjSize; w++) {
  26.             if (u->adj[w]->color == COLOR_WHITE) {
  27.                 for (int j = 0; j < graph->nrNodes; j++) {
  28.                     if (graph->v[j] == u->adj[w]) {
  29.                         poz = j;
  30.                         break;
  31.                     }
  32.                 }
  33.                 u->color = COLOR_GRAY;
  34.                 //graph->v[poz]->color = COLOR_GRAY;
  35.                 graph->v[poz]->dist = u->dist + 1;
  36.                 graph->v[poz]->parent = u;
  37.                 coada.push_back(u->adj[w]);
  38.             }
  39.         }
  40.  
  41.         graph->v[poz]->color = COLOR_BLACK;
  42.         u->color = COLOR_BLACK;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement