c语言中的广度优先搜索
我正在尝试用c实现bfs 这些是数据结构c语言中的广度优先搜索,c,data-structures,graph,breadth-first-search,C,Data Structures,Graph,Breadth First Search,我正在尝试用c实现bfs 这些是数据结构 typedef struct linkedlist { // linked list of ints (for use in Node) int index; struct linkedlist *next; } List; typedef struct { // a Node of a Graph char *name; List *outlist; // adjacency list int outdegree; int
typedef struct linkedlist { // linked list of ints (for use in Node)
int index;
struct linkedlist *next;
} List;
typedef struct { // a Node of a Graph
char *name;
List *outlist; // adjacency list
int outdegree;
int visited;// length of outlist
int indegree;
//double pagerank_score; //not needed for this exercise
} Node;
typedef struct {
// your code goes here
int MaxSize;
Node *table;
} Graph;
这是我的搜索码
#include "graph.h"
/* Good luck */
void bfs(Graph *mygraph){
//int i=0;
int u;
for(u=1;u<mygraph->MaxSize;u++)
mygraph->table[u].visited=0;
for(u=1;u<mygraph->MaxSize;u++){
if(mygraph->table[u].visited==0){
printf("%s \n",mygraph->table[u].name);
visit(u,mygraph);
}
}
}
void visit(int u,Graph *mygraph){
// i ++;
List *current;
mygraph->table[u].visited++;
current= mygraph->table[u].outlist;
while (current!=NULL) {
if(mygraph->table[current->index].visited==0)
printf("%i \n",current->index);
visit(current->index,mygraph);
current = current->next;}
}
#包括“graph.h”
/*祝你好运*/
无效bfs(图*mygraph){
//int i=0;
国际大学;
对于(u=1;uMaxSize;u++)
mygraph->table[u]。访问量=0;
对于(u=1;uMaxSize;u++){
如果(mygraph->table[u]。已访问==0){
printf(“%s\n”,mygraph->table[u].name);
访问(u,mygraph);
}
}
}
无效访问(int u,图形*mygraph){
//i++;
列表*当前;
mygraph->table[u]。已访问++;
current=mygraph->table[u]。大纲视图;
while(当前!=NULL){
如果(mygraph->表[当前->索引]。已访问==0)
printf(“%i\n”,当前->索引);
访问(当前->索引,mygraph);
当前=当前->下一步;}
}
由于某种原因,我不知道为什么我的实现是错误的?这里有一些优化,但您的代码看起来基本正确(我还没有完成我自己的BFS实现)。下面是应该考虑的:
for(u=1;u<mygraph->MaxSize;u++){
if(mygraph->table[u].visited==0){ /* Silly */
(u=1;uMaxSize;u++)的{
如果(mygraph->table[u]。已访问==0){/*0*/
你应该使用调试器来找出它在哪里出错。你能通过GDB运行它并显示你的程序在哪里出错的回溯吗?现在空白很便宜。不要害怕使用它。为current->index添加一些健全的检查,并确保outlist和next都是有效的指针。换句话说,确保你的图形设置在正确的位置在你走之前。对于(u=1;…)这个
看起来是错误的。通常是从0开始(对于(u=0;…)
)