0% found this document useful (0 votes)
8 views2 pages

Dsa Graph Bfs

The document contains a C++ program implementing the Breadth-First Search (BFS) algorithm for traversing a graph. It includes a function to perform BFS on a graph represented as an adjacency list and demonstrates its usage with a hardcoded undirected graph of 5 nodes. The file was created on July 29, 2025, and last modified on July 30, 2025.

Uploaded by

yaspdarekar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Dsa Graph Bfs

The document contains a C++ program implementing the Breadth-First Search (BFS) algorithm for traversing a graph. It includes a function to perform BFS on a graph represented as an adjacency list and demonstrates its usage with a hardcoded undirected graph of 5 nodes. The file was created on July 29, 2025, and last modified on July 30, 2025.

Uploaded by

yaspdarekar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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;
}

You might also like