Lintcode127 Topological Sorting solution 题解

【题目描述】

Given an directed graph, a topological order of the graph nodes is defined as follow:

·For each directed edgeA -> Bin 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.

给定一个有向图,图节点的拓扑排序被定义为:

·对于每条有向边A--> B,则A必须排在B之前

·拓扑排序的第一个节点可以是任何在图中没有其他节点指向它的节点

找到给定图的任一拓扑排序

【注】:你可以假设图中至少存在一种拓扑排序


【题目链接】

www.lintcode.com/en/problem/topological-sorting/


【题目解析】

1) 计算所有点的入度,用HashMap保存。

2) 将入度为0的点加入queue中和result中,将queue中节点出队,将出队节点所有neighbor的入度减少1。

3) 重复2直到所有点都被加入result中。

需要注意的是,如果有对HashMap做删除操作,不能再用原来的迭代器继续迭代,需要从头用新的迭代器进行迭代。


【参考答案】

www.jiuzhang.com/solutions/topological-sorting/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值