【发布时间】:2019-07-25 07:05:26
【问题描述】:
我在 Leetcode https://leetcode.com/problems/course-schedule/discuss/58509/18-22-lines-C++-BFSDFS-Solutions 上看到了下面使用 DFS 实现的拓扑排序
现在让我感到困惑的部分是用于顶级排序的有向图的表示。图表创建如下:
vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph(numCourses);
for (auto pre : prerequisites)
graph[pre.second].insert(pre.first);
return graph;
}
让我困惑的是这一行:
graph[pre.second].insert(pre.first);
大概图被表示为一个邻接表;如果是这样,为什么每个节点都由传入边而不是传出边表示?有趣的是,如果我像这样翻转 pre.second 和 pre.first:
graph[pre.first].insert(pre.second);
顶级排序仍然有效。但是,似乎大多数相同问题的实现都使用前一种方法。这是否适用于所有有向图?我在本科学位中被教导,有向图的邻接列表应该包含每个节点传出节点的列表。对于邻接表的表示,输入节点和输出节点的选择是任意的吗?
【问题讨论】:
标签: c++ algorithm data-structures graph-theory topological-sort