Created
April 1, 2024 00:52
-
-
Save YuanLiou/fe000a335a7ad0d702bee48117950f1e to your computer and use it in GitHub Desktop.
KahnsAlgorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.*; | |
| public class KahnsAlgorithm { | |
| public static void main(String[] args) { | |
| // Graph representation (adjacency list) | |
| List<List<Integer>> adjList = new ArrayList<>(); | |
| for (int i = 0; i < 4; i++) { | |
| adjList.add(new ArrayList<>()); | |
| } | |
| // Adding edges: A->B, A->C, B->D, C->D | |
| adjList.get(0).add(1); | |
| adjList.get(0).add(2); | |
| adjList.get(1).add(3); | |
| adjList.get(2).add(3); | |
| List<Integer> result = topologicalSort(adjList, 4); | |
| // Print the topological order | |
| for (int i : result) { | |
| System.out.print((char) ('A' + i) + " "); | |
| } | |
| } | |
| public static List<Integer> topologicalSort(List<List<Integer>> adjList, int numCourses) { | |
| int[] inDegree = new int[numCourses]; | |
| for (List<Integer> edges : adjList) { | |
| for (int edge : edges) { | |
| inDegree[edge]++; | |
| } | |
| } | |
| Queue<Integer> queue = new LinkedList<>(); | |
| for (int i = 0; i < numCourses; i++) { | |
| if (inDegree[i] == 0) { | |
| queue.add(i); | |
| } | |
| } | |
| List<Integer> topilogicalOrder = new ArrayList<>(); | |
| while (!queue.isEmpty()) { | |
| int course = queue.poll(); | |
| topilogicalOrder.add(course); | |
| for (int nextCourse : adjList.get(course)) { | |
| inDegree[nextCourse]--; | |
| if (inDegree[nextCourse] == 0) { | |
| queue.add(nextCourse); | |
| } | |
| } | |
| } | |
| if (topilogicalOrder.size() != numCourses) { | |
| throw new IllegalArgumentException("Cycle detected in the graph"); | |
| } | |
| return topilogicalOrder; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment