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 | /** * Definition for Directed graph. * class DirectedGraphNode { * int label; * ArrayList<DirectedGraphNode> neighbors; * DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); } * }; */ public class Solution { /** * @param graph: A list of Directed graph node * @return: Any topological order for the given graph. */ public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) { // write your code here //build adjacency list and then dfs to build output ArrayList<DirectedGraphNode> result = new ArrayList<DirectedGraphNode>(); if(graph==null||graph.size()==0)return result; //mark neighbors, and their referred times HashMap<DirectedGraphNode, Integer> map = new HashMap(); for (DirectedGraphNode node : graph) { for (DirectedGraphNode neighbor : node.neighbors) { if (map.containsKey(neighbor)) { map.put(neighbor, map.get(neighbor) + 1); } else { map.put(neighbor, 1); } } } //adding the start nodes the first Queue<DirectedGraphNode> q = new LinkedList<DirectedGraphNode>(); for (DirectedGraphNode node : graph) { if (!map.containsKey(node)) { q.offer(node); result.add(node); } } //then adding the neighbors while (!q.isEmpty()) { DirectedGraphNode node = q.poll(); for (DirectedGraphNode n : node.neighbors) { map.put(n, map.get(n) - 1);//descrease the counter if (map.get(n) == 0) { result.add(n);//add neighbor node when its reference becomes 0 //all its parents have been added q.offer(n);//start to process itself } } } return result; } } |
Quick tips or notes that probably reflects 20 percent of knowledge that usually does 80 percent of job.
Sunday, July 17, 2016
Topological Sorting
This is one algorithm I want to remember. My first thought is to build adjacency list and then traversal it. That would be wrong because child might appears before some of its parent.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment