简体   繁体   English

谁能解释一下这个 BFS 代码是如何工作的?

[英]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.此代码来自我错过的 class,现在我很难理解这一点。 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. q是 BFS 的典型队列(先进先出,FIFO)。 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). f指向队列的前部(从中提取值),而队列的后部r (将新值添加到队列中)。

The queue first is empty, and the neighbors j of current vertex v are added to the queue (at its "rear" side).队列首先是空的,当前顶点v的邻居j被添加到队列中(在其“后”侧)。 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.当一个顶点j在队列中时,它的visit[j]置为1,否则为0。这是为了防止同一个顶点被两次添加到队列中。

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).现在它被认为是访问过的,所以visited[v]现在设置为1 并且visit[v]被清除(这有点矫枉过正,但没关系)。 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.由于有n个顶点,当外循环迭代n次时,它们都会被访问。 That is what k counts.这就是k的重要性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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