Professional Documents
Culture Documents
DAA Worksheet 3.1
DAA Worksheet 3.1
DAA Worksheet 3.1
EXPERIMENT: 3.1
1. Aim:
Develop a program and analyze complexity to do a depth-first search
(DFS) on an undirected graph. Implementing an application of DFS such as
(i) to find the topological sort of a directed acyclic graph, OR (ii) to find a
path from source to goal in a maze.
2. Objective:
Develop a C++ program to perform Depth-First Search (DFS) on an
undirected graph.
Implement an application of DFS for either of the following:
• Topological Sort: Find the topological ordering of a Directed Acyclic
Graph (DAG). Topological sorting is used in various applications,
such as task scheduling and dependency resolution.
• Path Finding: Find a path from a source node to a goal node in a
maze or a graph. This can be used for solving maze navigation or
route planning problems.
3. Program code:
#include <iostream>
#include <vector>
#include <stack>
class Graph {
private:
int V;
vector<vector<int>> adj;
public:
Graph(int vertices) : V(vertices) {
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
adj.resize(V);
}
stack.push(v);
}
void topologicalSort() {
vector<bool> visited(V, false);
stack<int> stack;
int main() {
// Create a directed acyclic graph
Graph graph(6);
graph.addEdge(5, 2);
graph.addEdge(5, 0);
graph.addEdge(4, 0);
graph.addEdge(4, 1);
graph.addEdge(2, 3);
graph.addEdge(3, 1);
cout << "Topological Sort of the Directed Acyclic Graph:" << endl;
graph.topologicalSort();
return 0;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Output:
Time Complexity:
The time complexity of finding the topological sort of a DAG using DFS is O (V + E),
where: