I am completing a class lab which takes an adjacency matrix, and determines connectivity among vertices. Although my code runs, it does not give the correct results.
I believe there is a problem with the the second if statement in my while loop. any help is greatly appreciated. Code is below:
#include "graph.h"
#include <assert.h>
using namespace std;
bool Graph::connected(int v,int w) {
int visited[SIZE] ={0};
if (v == w)
return adj_matrix[v][v];
Queue<int> Q;
Q.Enqueue(v);
while (!Q.empty()) {
int curr = Q.Dequeue();
if (curr == w)
return true;
int z=0;
for (int i=0; i<SIZE; i++) {
if (adj_matrix[curr][z]==1 && visited[i]==false) {
Q.Enqueue(z);
visited[i]==true;
}
}
}
return false;
}
This is the output I am receiving:
0 0 1 0
0 0 0 0
0 0 0 0
0 0 0 1
vertex 0 is connected to vertices:
vertex 1 is connected to vertices:
vertex 2 is connected to vertices:
vertex 3 is connected to vertices: 3
Which is clearly missing another connection between 0 and 2 correct?
Look closely at your use of the variables i and z. It appears that z is assigned the value 0, and never changed after that. You may want to try using more descriptive variable names to avoid this sort of confusion.