From 23c55cab1300e12551586ed8185db27a11714d05 Mon Sep 17 00:00:00 2001 From: Harshit singh Date: Sun, 28 Dec 2025 12:19:12 +0530 Subject: [PATCH] Refactor BFS implementation for improved readability and safety --- BfsCpp | 105 ++++++++++++++++++++++++++++++--------------------------- 1 file changed, 56 insertions(+), 49 deletions(-) diff --git a/BfsCpp b/BfsCpp index a5025ee..08dbf27 100644 --- a/BfsCpp +++ b/BfsCpp @@ -1,58 +1,65 @@ +// } Driver Code Ends - // } Driver Code Ends - +/* +Algorithm: Breadth First Search (BFS) +Time Complexity: O(V + E) +Space Complexity: O(V) +*/ class Solution { public: - vectorbfsOfGraph(int V, vector adj[]){ - vector bfs; - vector vis(V, 0); - queue q; - q.push(0); - vis[0] = 1; - while(!q.empty()) { - int node = q.front(); - q.pop(); - bfs.push_back(node); - - for(auto it : adj[node]) { - if(!vis[it]) { - q.push(it); - vis[it] = 1; - } - } - } - - return bfs; - } + vector bfsOfGraph(int V, const vector adj[]) { + vector bfsTraversal; + vector visited(V, false); + queue q; + + // Start BFS from node 0 + q.push(0); + visited[0] = true; + + while (!q.empty()) { + int currentNode = q.front(); + q.pop(); + bfsTraversal.push_back(currentNode); + + for (int neighbor : adj[currentNode]) { + if (!visited[neighbor]) { + visited[neighbor] = true; + q.push(neighbor); + } + } + } + + return bfsTraversal; + } }; // { Driver Code Starts. -int main(){ - int tc; - cin >> tc; - // for multiple graphs - while(tc--){ - int V, E; - cin >> V >> E; - - vector adj[V]; - - for(int i = 0; i < E; i++) - { - int u, v; - cin >> u >> v; - adj[u].push_back(v); - // adj[v].push_back(u); // uncomment this for undirected graoh - } - // string s1; - // cin>>s1; +int main() { + int tc; + cin >> tc; + + while (tc--) { + int V, E; + cin >> V >> E; + + vector adj[V]; + + for (int i = 0; i < E; i++) { + int u, v; + cin >> u >> v; + adj[u].push_back(v); + // adj[v].push_back(u); // Uncomment for undirected graph + } + Solution obj; - vectorans=obj.bfsOfGraph(V, adj); - for(int i=0;i ans = obj.bfsOfGraph(V, adj); + + for (int node : ans) { + cout << node << " "; } - cout<