221902285-Algorithm Lab Report 4
221902285-Algorithm Lab Report 4
Student Details
Name ID
2. OBJECTIVES/AIM
The objective of this lab is to develop a Java program that utilizes the Depth-First Search
(DFS) algorithm to find the topological order of nodes in a graph. The program aims to
handle acyclic directed graphs and identify cycles to ensure a valid topological order.
3. IMPLEMENTATION
Question 1:
Write a program to find the topological order of nodes of a graph using DFS.
Code:
package GraphTheory;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
cycleCheck[source] = false;
result.push(source);
}
try {
Scanner sc = new Scanner(file);
nodeNo = sc.nextInt();
edgeNo = sc.nextInt();
for (int i = 0; i < nodeNo; i++) {
list.add(new ArrayList<>());
}
while (sc.hasNextLine()) {
int s = sc.nextInt();
int d = sc.nextInt();
list.get(s).add(d);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
}
System.out.println("Topological Order:");
while (!result.empty()) {
System.out.print(result.pop() + " ");
}
}
}
5. TEST RESULT / OUTPUT
The Graph:
6. Discussion
The implemented program successfully achieves the objective of finding the topological
order of nodes in a directed acyclic graph. The DFS algorithm ensures a systematic
exploration of the graph, and the cycle detection mechanism prevents the algorithm from
producing an incorrect topological order for cyclic graphs.