20BCS5977 - Daa Lab Worksheet 3.1
20BCS5977 - Daa Lab Worksheet 3.1
1. Aim:
2. Task to be done:
To implement DFS.
3. Algorithm:
Step 1: SET STATUS = 1 (ready state) for each node in G
Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until STACK is empty
Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
Step 5: Push on the stack all the neighbours of N that are in the ready state (whose
STATUS = 1) and set their
STATUS = 2 (waiting state)[END OF LOOP]
Step 6: EXIT
Code:
#include <bits/stdc++.h>
using namespace std;
void Graph::DFS(int v)
{
// Mark the current node as visited and
// print it
visited[v] = true;
cout << v << " ";
// Driver's code
int main()
{
// Create a graph given in the above diagram
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
// Function call
g.DFS(2);
return 0;
}
5. Complexity Analysis:
The Time complexity: O(V + E), where V is the number of vertices and E is the number of
edges in the graph.
6. Result: