Topological Sorting
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.
Find any topological order for the given graph.
Notice
You can assume that there is at least one topological order in the graph.
Clarification
Example
For graph as follow:
The topological order can be:
[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...
Challenge
View Code
Can you do it in both BFS and DFS?
BFS:
拓扑排序,有很多衍生题,比如选课系列。
如果一个图,有先后顺序关系,就要想一想拓扑排序的套路。
1,需要统计入度(in-degree).
2, 需要一个数据结构存放(node <--> in-degree)关系,这题中由于用的是node class,所以只能用map储存这种对应关系。
如果node可以用 0 - n-1 的整数代表,那么就可以直接用 List[size()] 来表示。
3,找到起始点,即indegree = 0 的点。
4,从起始点按照入度从小到大顺序开始bfs遍历。
5,按照所需返回结果。
/** * 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) { // use indegree ArrayList<DirectedGraphNode> result = new ArrayList<>(); if (graph == null) { return result; } Map<DirectedGraphNode, Integer> map = new HashMap<>(); Queue<DirectedGraphNode> queue = new LinkedList<>(); 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); } } } // Queue<DirectedGraphNode> q = new LinkedList<DirectedGraphNode>(); for (DirectedGraphNode node : graph) { if (!map.containsKey(node)) { queue.offer(node); result.add(node); } } while (!queue.isEmpty()) { DirectedGraphNode node = queue.poll(); for (DirectedGraphNode neighbor : node.neighbors) { map.put(neighbor,map.get(neighbor) - 1); if (map.get(neighbor) == 0) { queue.offer(neighbor); result.add(neighbor); } } } return result; } }