编写一个程序来使用深度搜索(DFS)算法解决拓扑排序问题
I want to use topological sorting using Depth First Search (DFS) for the given problem (the directed graph attached below).
Could you please help by writing the appropriate code for the given problem using any programming language?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
回顾:如果图中的所有边缘从较高的顶点到较低数字的顶点(或相反的方式),则图表的排序是拓扑排序。
这意味着,如果拥有一个顶点
v
,您将能够以某种方式访问所有可从v
访问的顶点,并给它们的数字低于您给出的数字代码> v ,然后所有的边缘从v
中>> v 将导致编号低于v
的顶点,因此它们将符合拓扑排序的定义。现在,我们的目标是实现上述所有顶点。
回想一下DFS在这里可能很有用,因为DFS访问了可从给定顶点访问的所有顶点。
我们必须为所有顶点运行DFS,但是由于DFS是一种递归算法,因此它将自行运行,以从可从运行DFS的其他顶点访问所有顶点。因此,我们必须为所有顶点运行DFS,以DFS函数的 exit 的顺序编号,因为在DFS函数的末尾,我们知道从给定顶点访问的所有顶点都已访问。
这是C ++中的一些示例代码:
这称为a
祝您大学课程好运!
To recap: an ordering of the vertices of a graph is a topological sorting if all edges in the graph lead from higher-numbered vertices to lower-numbered vertices (or the other way around).
This means, that if, having a vertex
V
, you'd be able to somehow visit all vertices accessible fromV
and give them numbers lower than the number you give toV
, then all edges going out ofV
will lead to vertices numbered lower thanV
, so they will conform to the definition of a topological sorting.It is now our goal to achieve the above for all vertices.
Recall that a DFS could be useful here, because a DFS visits all vertices accessible from a given vertex.
We must run the DFS for all vertices, but since the DFS is a recursive algorithm, it will run itself for all vertices accessible from other vertices for which the DFS is run. Thus, we must run the DFS for all vertices, numbering the vertices in the order in which we exit from the DFS function, because at the end of the DFS function we know that all vertices accessible from a given vertex have been visited.
Here's some sample code in C++:
This is called a post-order ordering and is a very common way to topologically sort a directed graph. You can then easily check if the topological sorting exists by verifying that all edges lead from a higher-numbered vertex to a lower-numbered vertex.
Good luck with your university course!