Skip to content

Commit 13035ec

Browse files
authored
Update main.cpp
1 parent 0bf4bd6 commit 13035ec

File tree

1 file changed

+46
-3
lines changed
  • 23 - Graph Data Structure Problems/02 - BFS Traversal in Graph

1 file changed

+46
-3
lines changed

23 - Graph Data Structure Problems/02 - BFS Traversal in Graph/main.cpp

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class Graph {
2222
}
2323
}
2424

25-
// Function to perform BFS traversal
25+
// Iterative BFS traversal
2626
void bfs(int startNode) {
2727
vector<bool> visited(adjacencyList.size(), false); // Visited array
2828
queue<int> q; // Queue for BFS
@@ -31,7 +31,7 @@ class Graph {
3131
visited[startNode] = true;
3232
q.push(startNode);
3333

34-
cout << "BFS Traversal: ";
34+
cout << "BFS Traversal (Iterative): ";
3535

3636
while (!q.empty()) {
3737
int currentNode = q.front();
@@ -50,6 +50,46 @@ class Graph {
5050
}
5151
cout << endl;
5252
}
53+
54+
// Recursive BFS traversal
55+
void bfsRecursiveHelper(int startNode, vector<bool>& visited, queue<int>& q) {
56+
if (q.empty()) {
57+
return; // Base case: queue is empty, stop recursion
58+
}
59+
60+
int currentNode = q.front();
61+
q.pop();
62+
63+
// Process the current node (e.g., print it)
64+
cout << currentNode << " ";
65+
66+
// Visit all unvisited neighbors
67+
for (int neighbor : adjacencyList[currentNode]) {
68+
if (!visited[neighbor]) {
69+
visited[neighbor] = true;
70+
q.push(neighbor);
71+
}
72+
}
73+
74+
// Recursive call with the updated queue
75+
bfsRecursiveHelper(startNode, visited, q);
76+
}
77+
78+
void bfsRecursive(int startNode) {
79+
vector<bool> visited(adjacencyList.size(), false); // Visited array
80+
queue<int> q; // Queue for BFS
81+
82+
// Start BFS from the startNode
83+
visited[startNode] = true;
84+
q.push(startNode);
85+
86+
cout << "BFS Traversal (Recursive): ";
87+
88+
// Start recursive BFS traversal
89+
bfsRecursiveHelper(startNode, visited, q);
90+
91+
cout << endl;
92+
}
5393
};
5494

5595
int main() {
@@ -65,8 +105,11 @@ int main() {
65105
g.addEdge(1, 4);
66106
g.addEdge(2, 5);
67107

68-
// Perform BFS traversal starting from node 0
108+
// Perform BFS traversal starting from node 0 (Iterative)
69109
g.bfs(0);
70110

111+
// Perform BFS traversal starting from node 0 (Recursive)
112+
g.bfsRecursive(0);
113+
71114
return 0;
72115
}

0 commit comments

Comments
 (0)