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. Part2:(Exercise 18.04) Problem Description Finish the implementation of BreadthFirstSearch. Take your solution from the preceding exercise and replace the stack with a queue. Requirement Please complete the function bfs in the file p2Traverse.cpp using queue
#include #include #include #include #include #include #include "CSC3002OJActive/assignment6/simplegraph.h" using namespace std;
void bfs(Node *start) { cout << "Breadth First Search" << endl;
}
void dfs(Node *start) { cout<< "Depth First Seacrh"<< endl; }
int main(){ SimpleGraph airline; readGraph(airline, cin); cout << "DFS at Portland ...." << endl; dfs(airline.nodeMap.at("Portland")); cout << "BFS at Portland ...." << endl; bfs(airline.nodeMap.at("Portland")); return 0; }
- Assistant
Solution:
void bfs(Node start) { cout << "Breadth First Search" << endl; queue<Node> q; // create a queue to store unexplored nodes set<Node*> visited; // create a set to store visited nodes q.push(start); // push the starting node to the queue visited.insert(start); // mark it as visited while (!q.empty()) { // while there are unexplored nodes in the queue Node* current = q.front(); // get the topmost node from the queue q.pop(); // remove it from the queue cout << current->name << endl; // visit the current node for (auto neighbor : current->neighbors) { // for each neighbor of the current node if (!visited.count(neighbor)) { // if the neighbor has not been visited visited.insert(neighbor); // mark it as visited q.push(neighbor); // push it to the queue } } } }