开发者

breadth first search in c

i am trying to implement a bfs in c

these are the data structures

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;

this is my search code

#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;}

}

this segfaults for some reason i do not know why is my implementation wrong ?


A few optimizations here, but your code looks mostly correct (I haven't finished my own BFS implementation yet). Here's what to think about:

  1. You're checking for visited == 0 unnecessarily - many times over. You've already set your node as visited, there's no need to check if is equal to zero.

     for(u=1;u<mygraph->MaxSize;u++){
         if(mygraph->table[u].visited==0){ /* Silly */
    
  2. Consider if you have allocated each block of memory that all your pointers are pointing to. That's probably the source of your segmentation fault.

  3. Whitespace, damn it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜