127题 Topological Sorting

该博客讨论了拓扑排序的概念,它是一种为有向无环图(DAG)的节点排列顺序的方法,确保每条有向边的起点在终点之前。提供的Java代码实现了一个高效的拓扑排序算法,首先计算每个节点的入度,然后使用队列存储入度为0的节点,逐步处理图中的节点,将其添加到排序列表中。该算法能保证找到至少一种有效的拓扑排序顺序。

Topological Sorting

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

/**
 * Definition for Directed graph.
 * class DirectedGraphNode {
 *     int label;
 *     List<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> result = new ArrayList<DirectedGraphNode>();
        Map<DirectedGraphNode, Integer> indegree = new HashMap<>();
        Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>() ;
        for(DirectedGraphNode node : graph){
            for(DirectedGraphNode neighbor : node.neighbors){
                if(indegree.containsKey(neighbor)){
                    indegree.put(neighbor , indegree.get(neighbor)+1);
                }else{
                    indegree.put(neighbor , 1);
                }
            }
        }
        for(DirectedGraphNode node : graph){
            if(! indegree.containsKey(node)){
                queue.offer(node) ;
                result.add(node) ;
            }
        }
        while(! queue.isEmpty()){
            DirectedGraphNode node = queue.poll() ;
            for(DirectedGraphNode neighbor : node.neighbors){
                indegree.put(neighbor, indegree.get(neighbor)-1);
                if (indegree.get(neighbor) == 0){
                    queue.offer(neighbor);
                    result.add(neighbor);
                }
            }
        }
       return result ;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值