Professional Documents
Culture Documents
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 to find the topological sort of a directed
acyclic graph
Objective:
Input/Apparatus Used:
Procedure/Algorithm:
For DFS:
Topological Sort:
TopologicalSort():
Reinitialize the 'visited' array to mark all vertices as unvisited
Reinitialize the stack for topological sorting
Sample Code:
#include <bits/stdc++.h>
#include <list>
#include <stack>
class Graph {
private:
int V; // Number of vertices
std::list<int>* adj; // Adjacency list
public:
Graph(int V);
void addEdge(int v, int w);
Graph::Graph(int V) {
this->V = V;
adj = new std::list<int>[V];
}
stack.push(v);
}
void Graph::DFS() {
bool* visited = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
}
while (!stack.empty()) {
std::cout << stack.top() << " ";
stack.pop();
}
delete[] visited;
}
void Graph::topologicalSort() {
bool* visited = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
}
std::stack<int> stack;
delete[] visited;
}
int main() {
Graph g(6); // Create a graph with 6 vertices
g.topologicalSort();
return 0;
}
Topological Sort:
The time complexity of topological sort is the same as DFS, which is O(V + E).
Space Complexity:
DFS Traversal:
The overall space complexity is O(V).
Topological Sort:
Similar to the DFS traversal, the space complexity for topological sort is O(V) due to the
recursion stack and the visited array.
Learning Outcomes:
I learned about DFS.
I learned about the Topological Sort and its functioning.
I learned about the time and space complexity of DFS and Topological Sort.
I learned about its implementation on both directed and undirected graph.