Hey guys Im a bit confused by this code for the BFS of a graph. This is chatgpt generated because I couldn't find a good example of a graph implemented with an adjacency matrix.
By the logic implemented here the visited vector is completely set to true by the second row of the graph. Is that supposed to be the case?
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// Function to perform BFS traversal
void BFS(vector<vector<int>>& graph, int start, vector<bool>& visited) {
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int current = q.front();
cout << current << " ";
q.pop();
// Visit all adjacent nodes of current node
for (int i = 0; i < graph.size(); ++i) {
if (graph[current][i] && !visited[i]) {
q.push(i);
visited[i] = true;
}
}
}
}
int main() {
// Example adjacency matrix representing a graph
vector<vector<int>> graph = {
{0, 1, 1, 0, 0},
{1, 0, 0, 1, 1},
{1, 0, 0, 0, 1},
{0, 1, 0, 0, 0},
{0, 1, 1, 0, 0}
};
// Number of vertices in the graph
int numVertices = graph.size();
// Initialize visited array to keep track of visited nodes
vector<bool> visited(numVertices, false);
cout << "BFS Traversal starting from node 0: ";
BFS(graph, 0, visited);
cout << endl;
return 0;
}