127.Topological Sorting
Last updated
Last updated
Given an directed graph, a topological order of the graph nodes is defined as follow:
For each directed edgeA ->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.
You can assume that there is at least one topological order in the graph.
Clarification
Learn more about representation of graphs
Example
For graph as follow:
The topological order can be:
图搜索相关的问题较为常见的解法是用DFS进行求解,分为三步走:
统计各定点的入度——只需统计节点在邻接列表中出现的次数即可知。
遍历图中各节点,找到入度为0的节点。
对入度为0的节点进行递归DFS,将节点加入到最终返回结果中。
拓扑排序除了可用DFS, 还可以用BFS具体方法为:
获得图中各节点的入度。存放在HashMap中,但是map中存放的是入度至少为1的点。
BFS首先遍历得到入度为0的点(不止一个,永不存在map中点得到),入队,进行下一次BFS
队列不为空时,弹出队顶元素并对其邻接节点进行BFS,现将其入度-1,如果他的入度变成0,就加入最终结果和队列中,重复此过程直至队列为空。