简体   繁体   中英

Can anyone explain me how this BFS code is working?

I am new to algorithms and data structures. This code is from the class I missed and now I am having difficulty understanding this. I could not understand what is happening after it asked for the initial vertex. Below is the code

#include<iostream>

#include<conio.h>

#include<stdlib.h>

using namespace std;
int i, j, k, e, n, f, r, v, c[10][10], q[10], visit[10], visited[10];
int main() {
  //clrscr();
  cout << "Enter number of nodes: ";
  cin >> n;
  cout << "Enter number of edges: ";
  cin >> e;
  cout << "enter edge details";
  for (k = 1; k <= e; k++) {
    cin >> i >> j;
    c[i][j] = 1;

  }
  cout << "enter initials vertex:";
  cin >> v;
  cout << "\n visited vertices are:" << v << "";
  visited[v] = 1;
  k = 1;
  while (k < n) {
    for (j = 1; j <= n; j++)
      if ((c[v][j] != 0) && (visited[j] != 1) && (visit[j] != 1)) {
        visit[j] = 1;
        q[r++] = j;
      }
    v = q[f++];
    cout << v << "";
    k++;
    visit[v] = 0;
    visited[v] = 1;
  }
}

q is the queue (First-in First-out, FIFO) that is typical for BFS. The front of the queue is pointed at by f (which is where values are pulled from), and the rear of the queue is pointed at by r (where new values are added to the queue).

The queue first is empty, and the neighbors j of current vertex v are added to the queue (at its "rear" side). When a vertex j is in the queue, its visit[j] is set to 1, otherwise it is 0. This is to prevent that the same vertex is added twice to the queue.

From the front of the queue, the next vertex is pulled. Now it is considered visited, so visited[v] is now set to 1 and visit[v] is cleared (this is a bit overkill, but OK). Again, this ensures that vertexes are only visited (and output) once.

By using a queue, we are sure that vertexes are visited in order of their distance (in terms of number of edges) from the initial vertex.

As there are n vertices, they will all be visited when the outer loop has iterated n times. That is what k counts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM