|
| 1 | +/** |
| 2 | + * Time : O() ; Space: O() |
| 3 | + * @tag : LintCode Copyright; Geeks for Geeks; Depth First Search; Breadth First Search |
| 4 | + * @by : Steven Cooks |
| 5 | + * @date: Sep 26, 2015 |
| 6 | + *************************************************************************** |
| 7 | + * Description: |
| 8 | + * |
| 9 | + * Given an directed graph, a topological order of the graph nodes is defined |
| 10 | + * as follow: |
| 11 | + * |
| 12 | + * For each directed edge A -> B in graph, A must before B in the order list. |
| 13 | + * The first node in the order can be any node in the graph with no nodes direct to it. |
| 14 | + * Find any topological order for the given graph. |
| 15 | + * |
| 16 | + *************************************************************************** |
| 17 | + * {@link http://www.lintcode.com/en/problem/topological-sorting/ } |
| 18 | + */ |
| 19 | +package _01_TopologicalSorting; |
| 20 | + |
| 21 | +import java.util.ArrayList; |
| 22 | +import java.util.Hashtable; |
| 23 | +import java.util.LinkedList; |
| 24 | +import java.util.Map; |
| 25 | +import java.util.Queue; |
| 26 | + |
| 27 | +/** see test {@link _01_TopologicalSorting.SolutionTest } */ |
| 28 | +public class Solution { |
| 29 | + |
| 30 | + public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) { |
| 31 | + Map<DirectedGraphNode, Integer> in = new Hashtable<>(); |
| 32 | + // count in-degree for each node in the graph |
| 33 | + for (DirectedGraphNode node : graph) { |
| 34 | + if (!in.containsKey(node)) { |
| 35 | + in.put(node, 0); |
| 36 | + } |
| 37 | + for (DirectedGraphNode neighbor : node.neighbors) { |
| 38 | + int degree = 1; |
| 39 | + if (in.containsKey(neighbor)) { |
| 40 | + degree += in.get(neighbor); |
| 41 | + } |
| 42 | + in.put(neighbor, degree); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + // put all nodes with zero in-degree |
| 47 | + Queue<DirectedGraphNode> zeros = new LinkedList<>(); |
| 48 | + for (DirectedGraphNode node : in.keySet()) { |
| 49 | + if (in.get(node) == 0) { |
| 50 | + zeros.offer(node); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // construct result |
| 55 | + ArrayList<DirectedGraphNode> res = new ArrayList<>(); |
| 56 | + while (!zeros.isEmpty()) { |
| 57 | + DirectedGraphNode node = zeros.poll(); |
| 58 | + res.add(node); |
| 59 | + for (DirectedGraphNode neighbor : node.neighbors) { |
| 60 | + int degree = in.get(neighbor) - 1; |
| 61 | + if (degree > 0) { |
| 62 | + in.put(neighbor, degree); |
| 63 | + } |
| 64 | + if (degree == 0) { |
| 65 | + zeros.offer(neighbor); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + return res; |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments