Eliminate the recursion from the implementation of depthFirstSearch by using a stack to…
- User
Eliminate the recursion from the implementation of depthFirstSearch by using a stack to store the unexplored nodes. At the beginning of the algorithm, you simply push the starting node on the stack. Then, until the stack is empty, you repeat the following operations:
- Pop the topmost node from the stack.
- Visit that node.
- Push its neighbors on the stack. Requirement Please complete the function dfs in the file p2Traverse.cpp using stack
- Assistant
#include #include #include
using namespace std;
// Graph class to represent the graph class Graph { int V; // number of vertices vector *adjList; // array of adjacency lists public: Graph(int V) { this->V = V; adjList = new vector[V]; } // function to add edge to the graph void addEdge(int u, int v) { adjList[u].push_back(v); adjList[v].push_back(u); } // function to perform Depth-First Search traversal void dfs(int startVertex) { bool visited[V]; for (int i = 0; i < V; i++) visited[i] = false; stack stack; stack.push(startVertex); while (!stack.empty()) { int currVertex = stack.top(); stack.pop(); if (!visited[currVertex]) { visited[currVertex] = true; cout << currVertex << " "; for (int neighbour : adjList[currVertex]) { if (!visited[neighbour]) { stack.push(neighbour); } } } } } };
// Driver code int main() { Graph g(5); // create a graph with 5 vertices g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(2, 4);
cout << "Depth-First Search traversal starting from vertex 0: "; g.dfs(0); // perform dfs starting from vertex 0
return 0; }