拓扑排序
Posted yunyouhua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了拓扑排序相关的知识,希望对你有一定的参考价值。
/** * 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> order = new ArrayList<>(); if (graph == null) { return order; } //1.count indegree Map<DirectedGraphNode, Integer> indegree = getIndegree(graph); //2.bfs Queue<DirectedGraphNode> queue = new LinkedList<>(); for (DirectedGraphNode node : graph) { if (indegree.get(node) == 0) { queue.offer(node); order.add(node); } } while (!queue.isEmpty()) { DirectedGraphNode node = queue.poll(); for (DirectedGraphNode neighbor : node.neighbors) { //node -> neighbor indegree.put(neighbor, indegree.get(neighbor) - 1); if (indegree.get(neighbor) == 0) { queue.offer(neighbor); order.add(neighbor); } } } //check 环状依赖 if (order.size() == graph.size()) { return order; } else { return null; } } private Map<DirectedGraphNode, Integer> getIndegree(ArrayList<DirectedGraphNode> graph) { //1.统计indegree,用map装 Map<DirectedGraphNode, Integer> indegree = new HashMap(); //初始化 for (DirectedGraphNode node : graph) { indegree.put(node, 0); } for (DirectedGraphNode node: graph) { for (DirectedGraphNode neighbor : node.neighbors) { //node -> neighbor indegree.put(neighbor, indegree.get(neighbor)+1); } } return indegree; } }
以上是关于拓扑排序的主要内容,如果未能解决你的问题,请参考以下文章