o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Genarate bfs code in cpp
- User
Genarate bfs code in cpp
- Assistant
Genarate bfs code in cpp
Certainly! Below is a C++ implementation of the Breadth-First Search (BFS) algorithm for traversing a graph. This code uses an adjacency list representation for the graph.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// Function to perform BFS on a graph
void BFS(int startVertex, const vector<vector<int>>& adjList, vector<bool>& visited) {
queue<int> q;
visited[startVertex] = true;
q.push(startVertex);
cout << "BFS Traversal starting from vertex " << startVertex << ": ";
while (!q.empty()) {
int current = q.front();
q.pop();
cout << current << " ";
// Iterate over all the adjacent vertices
for (int neighbor : adjList[current]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
cout << endl;
}
int main() {
// Number of vertices and edges
int numVertices, numEdges;
cout << "Enter the number of vertices in the graph: ";
cin >> numVertices;
cout << "Enter the number of edges in the graph: ";
cin >> numEdges;
// Adjacency list representation
vector<vector<int>> adjList(numVertices);
cout << "Enter the edges (u v) where u and v are vertex indices starting from 0:" << endl;
for (int i = 0; i < numEdges; ++i) {
int u, v;
cin >> u >> v;
// Add edge u -> v
adjList[u].push_back(v);
// If the graph is undirected, add edge v -> u as well
adjList[v].push_back(u);
}
// Visited vector to keep track of visited vertices
vector<bool> visited(numVertices, false);
// Perform BFS starting from vertex 0 (or any vertex you choose)
BFS(0, adjList, visited);
return 0;
}
How the code works:
Graph Representation:
vector<vector<int>> adjList), which is an efficient way to represent sparse graphs.BFS Function:
BFS function takes in the starting vertex, the adjacency list of the graph, and a visited vector.std::queue<int>) to keep track of the vertices to visit next.Main Function:
BFS function starting from vertex 0.Sample Input:
Enter the number of vertices in the graph: 5
Enter the number of edges in the graph: 4
Enter the edges (u v) where u and v are vertex indices starting from 0:
0 1
0 2
1 3
1 4
Sample Output:
BFS Traversal starting from vertex 0: 0 1 2 3 4
Note:
0 to numVertices - 1).u to v and not from v to u.visited vector is important to prevent revisiting the same vertex and to avoid infinite loops in cyclic graphs.Feel free to modify the code to suit your specific needs, such as changing the starting vertex or adapting the input method.
Not yet included in a published release.