#Help Understanding Graph BFS code

6 messages · Page 1 of 1 (latest)

earnest inlet
#

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;
}
dawn bison
earnest inlet
dawn bison
#

A graph may have one directional paths, like A[0][1] == 1 and A[1][0] == 0, than we can only go from node_0 to node_1

earnest inlet
#

ahhh ok yes I see how that input was formed now.