DAA Worksheet 3.1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

EXPERIMENT: 3.1

Student Name: Kumar Ankur UID: 21BCS2649


Branch: CSE Section/Group: 619-B
Semester: 5th Date of Performance:16-10- 2023
Subject Name: DAA Subject Code: 21CSH-311

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>

using namespace std;

class Graph {
private:
int V;
vector<vector<int>> adj;

public:
Graph(int vertices) : V(vertices) {
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

adj.resize(V);
}

void addEdge(int u, int v) {


adj[u].push_back(v);
}

void topologicalSortUtil(int v, vector<bool> &visited, stack<int> &stack) {


visited[v] = true;

for (int neighbor : adj[v]) {


if (!visited[neighbor]) {
topologicalSortUtil(neighbor, visited, stack);
}
}

stack.push(v);
}

void topologicalSort() {
vector<bool> visited(V, false);
stack<int> stack;

for (int i = 0; i < V; i++) {


if (!visited[i]) {
topologicalSortUtil(i, visited, stack);
}
}

cout << "Topological Sort: ";


while (!stack.empty()) {
cout << stack.top() << " ";
stack.pop();
}
cout << endl;
}
};

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:

• V is the number of vertices in the graph.


• E is the number of edges in the graph.

You might also like