0

I want to find any path (just one path is enough and it doesn't matter which one) and I want to find the sum of edge weights too. I used bfs for this problem but I can't get the right path. Here is my code. Can someone please help me and tell me where my errors are? Thanks!

 int bfs(struct Graph* graph, int startVertex,int endVertex) {
  struct queue* q = createQueue();
    int totalweight=0;
  graph->visited[startVertex] = 1;
  enqueue(q, startVertex);

  while (!isEmpty(q)) {

    int currentVertex = dequeue(q);

    if(currentVertex==endVertex){
        return;
    }
    struct node* temp = graph->adjLists[currentVertex];
    totalweight+=temp->weight;
     int adjVertex ;
    while (temp) {
        adjVertex = temp->vertex;

      if (graph->visited[adjVertex] == 0) {
        graph->visited[adjVertex] = 1;
        enqueue(q, adjVertex);
      }
      temp = temp->next;
    }
    printf("%d ",adjVertex);
  }

  return totalweight;
}
LMVogel
  • 779
  • 7
  • 28
alfered
  • 1
  • 1
  • Read [*Modern C*](https://modernc.gforge.inria.fr/) – Basile Starynkevitch Jun 08 '20 at 20:02
  • @BasileStarynkevitch okey i guess it will help me but can you just point out some of the wrongs – alfered Jun 08 '20 at 20:04
  • 1
    Welcome to Stack Overflow. Your question is too broad, but for one thing you seem to be using `totalweight` to add up the weights of *the first neighbors of every node you examine,* which has nothing to do with any path. I suggest you work it out on paper first: draw a simple graph, then execute BFS on it with a pencil, and note how you keep track of things. – Beta Jun 08 '20 at 20:50
  • Read also [*How to debug small programs*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). If your compiler is [GCC](http://gcc.gnu.org), compile [with](https://gcc.gnu.org/onlinedocs/gcc/Invoking-GCC.html) all warnings and debug info, so `gcc -Wall -Wextra -g`. Then learn to use [GDB](https://www.gnu.org/software/gdb/). Budget a full week of work. **StackOverflow is *not* a do-my-homework website**. See also [this C reference](https://en.cppreference.com/w/c) – Basile Starynkevitch Jun 09 '20 at 04:35
  • Read also the wikipage on [graphs](https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)) and on the [travelling salesman problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem). For your next question on StackOverflow, provide some [mre], and read http://norvig.com/21-days.html – Basile Starynkevitch Jun 09 '20 at 04:38

0 Answers0