【发布时间】:2016-07-22 17:20:18
【问题描述】:
我的任务是编写一些代码,从图表中获取节点列表,并确定它们是否处于正确的拓扑顺序。
图形在内存中表示如下:
typedef struct graph_t* Graph;
typedef struct node_t* Node;
struct node_t {
int id;
/*incoming edges*/
Linked_list incoming;
/*outgoing edges*/
Linked_list outgoing;
};
struct graph_t {
int order;
int size;
Node nodes;
};
为了简洁,我省略了链表的实现,但这只是链表的标准实现。
我还得到了以下算法(伪代码):
L <- topologically sorted list of nodes
V <- empty list of visited nodes
for each node n in L do
add n to V
for each node m reachable from n do
if m in V then L is not sorted
我确实了解拓扑顺序的定义,但我不明白这将如何或为什么会验证拓扑排序。
这个算法如何正确?另外,鉴于上述图表的表示,for each node m reachable from n do 线将如何实现?
另外,是否有比上述算法更好的算法来执行此任务?
【问题讨论】:
-
这不是调试或咨询服务。见How to Ask。
-
@Olaf 我不是在问如何实现该算法,只是为了解释它为什么起作用。这违反了提问的规则吗?如果是这样,我将删除我的帖子
-
请再次阅读我的评论。我没有说你要求实施。
标签: c algorithm graph topological-sort