Description
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.
Example
For graph as follow:
The topological order can be:
[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...
Solution
思路:先遍历整张图中入度为0的点,然后更新这个点neighbors的入度(-1),再遍历neighbors中入度为0的点
- 用一个hashMap存图中所有的点和对应的度数。初始化时,遍历图中所有点,对其邻点的度数加一。每取一个点,从map里找到其邻点的度数减一。
- 用一个queue存放所有当前度数为0的点,初始时,图中所有点加入map中后,遍历map,将所有度数为0的点加入queue。每从queue中poll出一个点,在更新其邻点度数的过程中,碰到度数为0的点,继续加入queue中。
/**
* 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
ArrayList<DirectedGraphNode> ret = new ArrayList<DirectedGraphNode>();
HashMap<DirectedGraphNode, Integer> map = new HashMap<DirectedGraphNode, Integer>();
Queue<DirectedGraphNode> q = new LinkedList<DirectedGraphNode>();
// put all node into map
for (DirectedGraphNode node : graph) {
if (!map.containsKey(node)) {
map.put(node, 0);
}
for (DirectedGraphNode neighbor : node.neighbors) {
int degree = 0;
if (map.containsKey(neighbor)) {
degree = map.get(neighbor);
}
map.put(neighbor, degree + 1);
}
}
// put all the nodes with 0 degrees into queue
for (DirectedGraphNode node : graph) {
if (map.get(node) == 0) {
q.offer(node);
}
}
while (!q.isEmpty()) {
DirectedGraphNode curNode = q.poll();
ret.add(curNode);
for (DirectedGraphNode neighbor : curNode.neighbors) {
int degree = map.get(neighbor);
if (degree == 1) {
q.offer(neighbor);
}
map.put(neighbor, degree - 1);
}
}
return ret;
}
}