diff --git a/Graph/04_BFS Traversal.md b/Graph/04_BFS Traversal.md index 58b54a4..8c9ef7a 100644 --- a/Graph/04_BFS Traversal.md +++ b/Graph/04_BFS Traversal.md @@ -36,4 +36,72 @@ return bfs; ### Complexities: Time Complexity: O(V + 2E). (While loop will run for V vertex, for loop will run for degrees of that vertex and degree=2×edges). -Space Complexity: O(3*N) ~ O(N). (2 Vector and 1 queue) \ No newline at end of file +Space Complexity: O(3*N) ~ O(N). (2 Vector and 1 queue) + + +#include +#include +#include +#include + +using namespace std; + +void bfs(int startNode, vector> &adj, int n) { + deque q; + vector visited(n, false); + + q.push_back(startNode); + visited[startNode] = true; + + while (!q.empty()) { + int node = q.front(); + q.pop_front(); + + // Instead of storing in a vector, directly print the node + cout << node << " "; + + for (auto &neighbor : adj[node]) { + if (!visited[neighbor]) { + q.push_back(neighbor); + visited[neighbor] = true; + } + } + } +} + +int main() { + int n = 5; // Example number of nodes + vector> adj(n); + + // Example graph setup (undirected) + adj[0].push_back(1); + adj[0].push_back(2); + adj[1].push_back(0); + adj[1].push_back(3); + adj[1].push_back(4); + adj[2].push_back(0); + adj[3].push_back(1); + adj[4].push_back(1); + + int startNode = 0; // Starting node, can be modified as needed + cout << "BFS traversal starting from node " << startNode << ": "; + bfs(startNode, adj, n); + + return 0; +} +