Professional Documents
Culture Documents
UID:- 19BCS2241
Student Name:- Kartik Guleria
Section/Group:- CSE-9/A
Branch:- CSE
Subject Code:- CSP-309
Subject Name:- DAA Lab
Depth First Search (DFS) AlgorithmDepth First Search (DFS) algorithmtraverses a graph in a depth
ward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs
in any iteration.
Algorithm :
Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
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
The topological sorting for a directed acyclic graph is the linear ordering of vertices. For every
edge U-V of a directed graph, the vertex u will come before vertex v in the ordering
Algorithm:
Input − The start vertex u, An array to keep track of which node is visited or not. A stack to
store nodes. Output − Sorting the vertices in topological sequence in the stack.
Begin
done
End
performTopologicalSorting(Graph)
Begin
initially mark all nodes as unvisited for all nodes v of the graph,
done
stack End
Code:
#include <bits/stdc++.h>
class Graph
public:
};
adj[v].push_back(w);
void Graph::DFS(int v)
visited[v] = true;
list<int>::iterator i;
if (!visited[*i])
DFS(*i); }
int main(
{
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)
g.DFS(2)
Return 0; }
Output: