mercredi 29 juin 2016

BFS taking twice the distance in undirected graph


could you help me out with this code(I got it from github because it's clear and follow the same logic that I do, also the same problem,I just added some details like predecessors that I'm using)? Well, I tried a lot of times but I couldn't figure out the problem, I don't understand why my bfs algorithm (and this one) the wrong distance in an undirected and weighted graph consider my graph is using matrix, but when I use bfs to travel from b to c, for example, I got 5 and not just 2 as the cost... and a to b I got 2, what is the right answer. a b c d a | 0 2 0 0 b | 2 0 0 3 c | 0 0 0 0 d | 0 3 0 0 Here is the code: const int branco = 0; const int cinza = 1; const int preto = 2; int bfs(int start, int target) { int color[countVertices]; queue<int> fila; dist = 0; predecessors.clear(); for (int i = 0; i < countVertices; i++) { color[i] = white; } color[start] = grey; fila.push(start); while (!fila.empty()) { int u = fila.front(); fila.pop(); if (u == target) return 1; for (int v = 0; v < countVertices; v++) { if (matriz[u][v] != 0 && color[v] == white) { color[v] = grey; fila.push(v); dist += matriz[u][v]; // sum weight predecessors.push_front(u); // predecessor } } color[u] = black; } return 0; }

Aucun commentaire:

Enregistrer un commentaire