首页 > 代码库 > 拓扑排序
拓扑排序
/** * 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; } }
拓扑排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。