|
| 1 | +package com.hellokoding.datastructure.graph; |
| 2 | + |
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.Deque; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +public class TopologicalSortByDFSRecursiveColor { |
| 9 | + static final int WHITE = 0, GRAY = 1, BLACK = 2; |
| 10 | + static boolean hasCycle = false; |
| 11 | + |
| 12 | + static void topologicalSortByDFSRecursive(GraphDirectedByAdjacencyList g, int v, int[] color, Deque<Integer> stack) { |
| 13 | + if (hasCycle) { |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + color[v] = GRAY; |
| 18 | + |
| 19 | + for (Integer w : g.adjacencyList.get(v)) { |
| 20 | + if (color[w] == GRAY) { |
| 21 | + hasCycle = true; |
| 22 | + } |
| 23 | + |
| 24 | + if (color[w] == WHITE) { |
| 25 | + topologicalSortByDFSRecursive(g, w, color, stack); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + color[v] = BLACK; |
| 30 | + stack.push(v); |
| 31 | + } |
| 32 | + |
| 33 | + static List<Integer> topologicalSort(GraphDirectedByAdjacencyList g) { |
| 34 | + int[] color = new int[g.V]; |
| 35 | + Deque<Integer> stack = new ArrayDeque<>(); |
| 36 | + hasCycle = false; |
| 37 | + |
| 38 | + for (int i = 0; i < g.V; i++) { |
| 39 | + if (color[i] == WHITE) { |
| 40 | + topologicalSortByDFSRecursive(g, i, color, stack); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return hasCycle ? new ArrayList<>() : new ArrayList<>(stack); |
| 45 | + } |
| 46 | + |
| 47 | + public static void printResult(List<Integer> sorted) { |
| 48 | + if (sorted.isEmpty()) { |
| 49 | + System.out.println("There are no topological orderings as the input graph is cyclic"); |
| 50 | + } else { |
| 51 | + sorted.forEach((x) -> System.out.printf("%d ", x)); |
| 52 | + System.out.println(); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + public static void main(String[] args) { |
| 57 | + GraphDirectedByAdjacencyList g1 = new GraphDirectedByAdjacencyList(5); |
| 58 | + g1.addEdge(0, 1); |
| 59 | + g1.addEdge(1, 2); |
| 60 | + g1.addEdge(2, 0); |
| 61 | + g1.addEdge(1, 3); |
| 62 | + g1.addEdge(2, 4); |
| 63 | + printResult(topologicalSort(g1)); |
| 64 | + |
| 65 | + GraphDirectedByAdjacencyList g2 = new GraphDirectedByAdjacencyList(4); |
| 66 | + g2.addEdge(0, 1); |
| 67 | + g2.addEdge(2, 0); |
| 68 | + g2.addEdge(2, 1); |
| 69 | + g2.addEdge(3, 2); |
| 70 | + printResult(topologicalSort(g2)); |
| 71 | + } |
| 72 | +} |
0 commit comments