1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
public class Solution {
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) { ArrayList<DirectedGraphNode> result = new ArrayList<DirectedGraphNode>(); if(graph == null || graph.size() == 0) { return result; } HashMap<DirectedGraphNode, Integer> map = new HashMap<DirectedGraphNode, Integer>(); for(DirectedGraphNode node: graph) { map.put(node, 0); } while (hasUnsorted(map, graph)) { DirectedGraphNode node = null; for (DirectedGraphNode temp : graph) { if (map.get(temp) == 0) { node = temp; } } sort(map, graph, result, node); } return result; } public boolean hasUnsorted(Map<DirectedGraphNode, Integer> map, ArrayList<DirectedGraphNode> graph){ for (DirectedGraphNode node : graph) { if (map.get(node) == 0) { return true; } } return false; } public void sort(Map<DirectedGraphNode, Integer> map, ArrayList<DirectedGraphNode> graph, ArrayList<DirectedGraphNode> result, DirectedGraphNode node){ if (map.get(node) != 0) { return; } map.put(node, 1); for (DirectedGraphNode next : node.neighbors) { sort(map, graph, result, next); } result.add(0, node); } }
|