我目前正在学习图表,而且我正在使用C.当我代表一个带有邻接列表的图表时,我需要一个BFS遍历的队列。但是,我对代码有一些问题 - 我不确定我是否掌握了队列的bfs遍历的概念。
我粘贴了下面的评论代码,希望它具有可读性。有人可以检查一下,或者至少提供一些关于如何以正确的方式解决这个问题的信息吗?
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;
}
}
}
答案 0 :(得分:0)
我没有看到任何明显的错误,但是你在这里展示的图形结构太简单了,无法使用BFS。每个节点最多只有一个传出边:next
指针。这只是一个链表,只有一个遍历;广度优先和深度优先是等价的,因为每个深度最多只有一个节点。
所以你真的只需要那个“可疑的”内循环,它将从一个节点开始,并沿着边缘到链表的末尾。