topological sorted

来源:互联网 发布:mysql 连接127.0.0.1 编辑:程序博客网 时间:2024/06/06 04:26

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.

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

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


原创粉丝点击