图序列化
我正在寻找一种简单的算法来“序列化”有向图。 特别是,我有一组执行顺序相互依赖的文件,我想在编译时找到正确的顺序。 我知道这一定是一件相当常见的事情 - 编译器一直在这样做 - 但我的谷歌今天一直很弱。 这个的“首选”算法是什么?
I'm looking for a simple algorithm to 'serialize' a directed graph. In particular I've got a set of files with interdependencies on their execution order, and I want to find the correct order at compile time. I know it must be a fairly common thing to do - compilers do it all the time - but my google-fu has been weak today. What's the 'go-to' algorithm for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果图表包含循环,那么您的文件如何存在允许的执行顺序?
在我看来,如果图表包含循环,那么你就没有解决方案,而这
上述算法正确报告。
If the graph contains cycles, how can there exist allowed execution orders for your files?
It seems to me that if the graph contains cycles, then you have no solution, and this
is reported correctly by the above algorithm.
我想出了一个相当幼稚的递归算法(伪代码):
最大的问题是它没有能力检测循环依赖关系 - 它可以进入无限递归(即堆栈溢出;-p)。 我能看到的唯一解决方法是将递归算法翻转为具有手动堆栈的交互式算法,并手动检查堆栈中是否有重复元素。
有人有更好的东西吗?
I've come up with a fairly naive recursive algorithm (pseudocode):
The biggest problem with this is that it has no ability to detect cyclic dependencies - it can go into infinite recursion (ie stack overflow ;-p). The only way around that that I can see would be to flip the recursive algorithm into an interative one with a manual stack, and manually check the stack for repeated elements.
Anyone have something better?
我希望需要此功能的工具只需以深度优先的方式遍历树,当它们到达叶子时,只需处理它(例如编译)并将其从图中删除(或将其标记为已处理,并处理具有所有叶子的节点)加工为叶子)。
只要它是 DAG,这种简单的基于堆栈的遍历就应该是微不足道的。
I would expect tools that need this simply walk the tree in a depth-first manner and when they hit a leaf, just process it (e.g. compile) and remove it from the graph (or mark it as processed, and treat nodes with all leaves processed as leaves).
As long as it's a DAG, this simple stack-based walk should be trivial.
拓扑排序(来自维基百科):
伪代码:
Topological Sort (From Wikipedia):
Pseudo code: