Topological Sorting

来源:互联网 发布:c语言whilet--的用法 编辑:程序博客网 时间:2024/05/29 15:44

拓扑排序非常重要的一种考题。
topological sort的重点在于如何找到排序的入口

java

/** * 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        if (graph == null) {            return null;        }        Map<DirectedGraphNode, Integer> map = new HashMap<>();        for (DirectedGraphNode node : graph) {            for (DirectedGraphNode val : node.neighbors) {                if (map.containsKey(val)) {                    map.put(val, map.get(val) + 1);                } else {                    map.put(val, 1);                }            }        }        Queue<DirectedGraphNode> queue = new LinkedList<>();        ArrayList<DirectedGraphNode> list = new ArrayList<>();        for (DirectedGraphNode node : graph) {            if (!map.containsKey(node)) {                queue.offer(node);                list.add(node);            }        }        while (!queue.isEmpty()) {            DirectedGraphNode node = queue.poll();            for (DirectedGraphNode val : node.neighbors) {                map.put(val, map.get(val) - 1);                if (map.get(val) == 0) {                    queue.offer(val);                    list.add(val);                }            }        }        return list;    }}

python

"""Definition for a Directed graph nodeclass DirectedGraphNode:    def __init__(self, x):        self.label = x        self.neighbors = []"""import Queueclass Solution:    """    @param: graph: A list of Directed graph node    @return: Any topological order for the given graph.    """    def topSort(self, graph):        # write your code here        if graph is None:            return None        mapping, arr, queue = {}, [], Queue.Queue()        for ele in graph:            for val in ele.neighbors:                if val in mapping:                    mapping[val] = mapping[val] + 1                else:                    mapping[val] = 1        for ele in graph:            if ele not in mapping:                arr.append(ele)                queue.put(ele)        while not queue.empty():            node = queue.get()            for ele in node.neighbors:                mapping[ele] = mapping[ele] - 1                if mapping[ele] == 0:                    queue.put(ele)                    arr.append(ele)        return arr