简体   繁体   English

使用队列遍历图BFS [C]

[英]Graph BFS traversal using a queue [C]

I'm studying graphs at the moment, and I'm using C. When I represent a graph with an adjacency list, I need a queue for a BFS traversal. 目前,我正在研究图形,并且正在使用C。当我用邻接表表示图形时,我需要一个队列来进行BFS遍历。 However, I'm having some issues with the code - I'm not sure if I grasped the concept of a bfs traversal with queues well. 但是,我的代码存在一些问题-我不确定我是否对队列的bfs遍历概念掌握得很好。

I pasted the commented code below, I hope it's readable. 我在下面粘贴了注释的代码,希望它可读。 Can someone check it out, or at least provide some info on how to pull this off the right way? 有人可以检查出来,还是至少提供一些有关如何以正确方式实现此目的的信息?

typedef struct {
   char name[21], surname[21];
   double gpa;
} STUDENT;

typedef struct {
   int index;
   struct graph *next;
   STUDENT s;
} GRAPH_NODE;

typedef struct {
   GRAPH_NODE *nodes[50];
   int n;
} GRAPH;

//QUEUE is also a struct, but no need to paste it here

void bfs(GRAPH g, int start) {
     QUEUE queue;
     queue.f = -1;
     queue.r = 0;
     int v;  //will hold the index of the node taken off the queue
             //         (the one that's processed)
     int visited[MAX] = {0};
     visited[start] = 1;

     addToQueue(&queue, start);     //first node is visited, goes to queue

     while (deleteFromQueue(&queue, &v)) {
         printf("%d. ", v+1);
         printStudent(g.nodes[v].s);

         GRAPH_NODE *current = g->nodes[v];
         current->index = v;  //not sure if this is right        

         //this is the part I'm suspicious about
         while (current) {
             int u = current->index;  
             if (!visited[u]) {
                 visited[u] = 1;
                 addToQueue(&queue, u);
             }
             current = current->next;
         }
     } 
 }

I don't see anything blatantly wrong, but the graph structure you show here is too simple to bother with BFS. 我没有看到任何明显的错误,但是您在此处显示的图形结构太简单了,无法使用BFS。 Every node has at most one outgoing edge: the next pointer. 每个节点最多具有一个输出边缘: next指针。 This is just a linked list, which has only one traversal; 这只是一个链表,只有一个遍历。 breadth-first and depth-first are equivalent as there is only at most one node at each depth. 广度优先和深度优先等效,因为每个深度最多只有一个节点。

So you really only need that "suspicious" inner loop, it will start from a node and follow the edges to the end of the linked list. 因此,您实际上只需要那个“可疑”的内部循环,它将从一个节点开始,并沿着边缘到链表的末尾。

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

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