Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Problem Statement. Given the graph class using the adjacency matrix representation, Implement the DFS algorithm on graph using the adjacency matrix representation. You have to
Problem Statement. Given the graph class using the adjacency matrix representation, Implement the DFS algorithm on graph using the adjacency matrix representation. You have to use the graph code as a starting point, and add the DFS method in the graph class similar to the BFS method already present in the Graph class.
// C++ implementation of the approach //#include#include #define MAX_VERTICES 20 #define SIZE 10 using namespace std; // Class for queue class Queue { int arr[MAX_VERTICES]; // array to store Queue elements int capacity; // maximum capacity of the Queue int front; // front points to front element in the Queue (if any) int rear; // rear points to last element in the Queue int count; // current size of the Queue public: Queue(int size = SIZE); // constructor // ~Queue(); // destructor int dequeue(); void enqueue(int x); int peek(); int size(); bool isEmpty(); bool isFull(); }; // Constructor to initialize Queue Queue::Queue(int size) { for(int i=0;i v = v; this->e = e; for (int row = 0; row < v; row++) { for (int column = 0; column < v; column++) { adj[row][column] = 0; } } } // Function to add an edge to the graph void Graph::addEdge(int start_v, int end_v) { // Considering a bidirectional edge (undirected graph) adj[start_v][end_v] = 1; adj[end_v][start_v] = 1; } // Function to perform BFS on the graph void Graph::BFS(int start) { // Visited vector to so that // a vertex is not visited more than once // Initializing the vector to false as no // vertex is visited at the beginning bool visited[MAX_VERTICES] = {false}; // vector visited(v, false); Queue q; // vector q; q.enqueue(start); // Set source as visited visited[start] = true; int u; while (!q.isEmpty()) { u = q.dequeue(); // Print the current node cout << u << " "; // For every adjacent vertex to the current vertex for (int v1 = 0; v1 < v; v1++) { if (adj[u][v1] == 1 && (!visited[v1])) // if node v1 is adjacent to u and not visited { // Push the adjacent node to the Queue q.enqueue(v1); // Set v1 as visited visited[v1] = true; } } } } // Driver code int main() { int v = 8, e = 4; // Create the graph Graph G(v, e); G.addEdge(1, 2); G.addEdge(1, 5); G.addEdge(2, 6); G.addEdge(5, 6); G.addEdge(6, 4); G.addEdge(5, 3); // G.addEdge(5, 6); G.BFS(1); }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started