Given an directed graph, a topological order of the graph nodes is defined as follow:
- For each directed edge A-->B in graph, A must before B in the order list.
- The first node in the order can be any node in the graph with no nodes direct to it.
For graph as follow:
The topological order can be:
[0, 1, 2, 3, 4, 5]
or
[0, 2, 3, 1, 5, 4]
or
....
Can you do it in both BFS and DFS?
Analysis:
A basica method is recording the pre nodes of every node, then find out a node without pre node in each iteration and delete this node from unvisited set.
DFS: use a recursive method, randomly pick up an unmakred node, before adding it into result list, recursively visite all its neighbors and add its neighbors into list first. In this way, we guarantee that all the nodes belong to some node's post nodes will be added to the result list first.
Solution 1:
1 /** 2 * Definition for Directed graph. 3 * class DirectedGraphNode { 4 * int label; 5 * ArrayListneighbors; 6 * DirectedGraphNode(int x) { label = x; neighbors = new ArrayList (); } 7 * }; 8 */ 9 public class Solution {10 /**11 * @param graph: A list of Directed graph node12 * @return: Any topological order for the given graph.13 */ 14 public ArrayList topSort(ArrayList graph) {15 ArrayList res = new ArrayList ();16 if (graph.size()==0) return res;17 18 //Construct hash map.19 Map > map = new HashMap >();20 for (DirectedGraphNode node: graph){21 Set set = new HashSet ();22 map.put(node,set);23 }24 for (DirectedGraphNode node : graph)25 for (DirectedGraphNode temp: node.neighbors)26 map.get(temp).add(node); 27 28 //Construct topological order sequence.29 int len = graph.size();30 while (graph.size()>0) {31 int index = 0;32 while (index
Solution 2 (DFS):
1 /** 2 * Definition for Directed graph. 3 * class DirectedGraphNode { 4 * int label; 5 * ArrayListneighbors; 6 * DirectedGraphNode(int x) { label = x; neighbors = new ArrayList (); } 7 * }; 8 */ 9 public class Solution {10 /**11 * @param graph: A list of Directed graph node12 * @return: Any topological order for the given graph.13 */ 14 public ArrayList topSort(ArrayList graph) {15 ArrayList res = new ArrayList ();16 if (graph.size()==0) return res;17 Map status = new HashMap ();18 for (DirectedGraphNode node: graph)19 status.put(node,0);20 21 while (hasUnsorted(status,graph)){22 DirectedGraphNode node = null;23 for (DirectedGraphNode temp : graph)24 if (status.get(temp)==0) node = temp;25 search(status, graph, res, node);26 }27 28 return res;29 30 }31 32 public boolean hasUnsorted(Map status, ArrayList graph){33 for (DirectedGraphNode node : graph)34 if (status.get(node)==0) return true;35 36 return false;37 }38 39 public void search(Map status, ArrayList graph, ArrayList res, DirectedGraphNode node){40 if (status.get(node)==1) System.out.println("It is not a DAG");41 if (status.get(node)==2) return;42 status.put(node,1);43 for (DirectedGraphNode next : node.neighbors)44 search(status,graph,res,next);45 status.put(node,2);46 res.add(0,node);47 }48 49 }