[LintCode] Topological Sorting [BFS & DFS]

415 查看

Problem

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]
...

Challenge

Can you do it in both BFS and DFS?

Note

先看BFS的做法:
建立哈希表map,存储graph中所有neighbors结点的入度。
然后建立空的队列q,将所有非依赖结点(如例子中的0结点,没有其它元素指向它,也可以理解为根节点)放入队列q和结果数组res
当队列q非空时,拿出q最后放入的元素cur。然后遍历cur的所有neighbors结点neighbor,并将遍历后的neighbor入度减1。若减1后入度为0,则这个结点遍历完成,放入结果数组res和队列q

再看DFS的做法:
建立HashSet<DirectedGraphNode> visited,标记遍历过的点node。递归dfs函数去遍历nodeneighbors,继续在visited中标记,使得所有点只遍历一次。
最深的点最先,根结点最后,加入结果数组res的头部(index = 0处)。

Solution

BFS

public class Solution {
    public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
        ArrayList<DirectedGraphNode> res = new ArrayList<>();
        Queue<DirectedGraphNode> queue = new LinkedList<>();
        Map<DirectedGraphNode, Integer> map = new HashMap<>();
        //把除了头结点外的结点放入map
        for (DirectedGraphNode n: graph) {
            for (DirectedGraphNode node: n.neighbors) {
                if (!map.containsKey(node)) map.put(node, 1);
                else map.put(node, map.get(node)+1);
            }
        }
        //找到头结点,放入queue和结果数组res
        for (DirectedGraphNode n: graph) {
            if (!map.containsKey(n)) {
                queue.offer(n);
                res.add(n);
            }
        }
        //对queue中的结点的neighbors进行BFS(入度减1),当neighbor的入度减小为0,放入queue和结果数组res
        while (!queue.isEmpty()) {
            DirectedGraphNode n = queue.poll();
            for (DirectedGraphNode node: n.neighbors) {
                map.put(node, map.get(node)-1);
                if (map.get(node) == 0) {
                    res.add(node);
                    queue.offer(node);
                }
            }
        }
        return res;
    }
}

DFS Recursion

public class Solution {
    public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
        ArrayList<DirectedGraphNode> res = new ArrayList();
        Set<DirectedGraphNode> visited = new HashSet();
        for (DirectedGraphNode node: graph) {
            if (!visited.contains(node)) {
                dfs(node, visited, res);
            }
        }
        return res;
    }
    public void dfs(DirectedGraphNode node, Set<DirectedGraphNode> visited, List<DirectedGraphNode> res) {
        visited.add(node);
        for (DirectedGraphNode n: node.neighbors) {
            if (!visited.contains(n)) dfs(n, visited, res);
        }
        res.add(0, node);
    }
}