Code Notes Buddy - File Export
File Information
File Name: BFS
File Type: CPP
Notebook: DSA
Folder: Graph
Created: 29/07/2025
Last Modified: 30/07/2025
Size: 964 characters
File Content
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void bfs(int start, const vector<vector<int>>& adjList, int n) {
vector<bool> visited(n + 1, false);
queue<int> q;
visited[start] = true;
[Link](start);
while (![Link]()) {
int node = [Link]();
[Link]();
cout << node << " ";
for (int neighbor : adjList[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
[Link](neighbor);
}
}
}
cout << endl;
}
int main() {
int n = 5; // number of nodes
vector<vector<int>> adjList(n + 1); // 1-based indexing
// Hardcoded edges (undirected graph)
adjList[1] = {2, 3};
adjList[2] = {1, 4};
adjList[3] = {1, 5};
adjList[4] = {2};
adjList[5] = {3};
int start = 1; // Starting node for BFS
bfs(start, adjList, n);
return 0;
}