题目:
题解:
- 拓扑排序裸题
- 算法步骤:
- 1)遍历边的数组
prerequisites
建立图的邻接表
- 2)使用队列来存放入度为0的顶点,从而避免重复检测入度为0的顶点
- 3)删除入度为0的点,以及删除该点为起点的边,并统计删除入度为0的顶点个数
- 4)若有向图无环,则count等于顶点数numCounses;否则有向图有环,则count会小于顶点数numCounses
拓扑排序算法思路:
- 1)在有向图中选一个入度为0的顶点且输出之
- 2)从图中删除该顶点和所有以它为弧尾的弧
- 3)重复上述两步,直至全部顶点均已输出,或者当前图中不存在无前驱的顶点为止。后者表示的是该有向图存在环。
代码如下:
// 2022/4/8 代码
const int N = 1e5+10;
vector<int> graph[N];
class Solution {
public:
// 建立邻接表,进行拓扑排序
bool canFinish(int n, vector<vector<int>>& g) {
fill(graph,graph+n,vector<int> ());
vector<int> indegrees(n);
// 建立邻接表以及统计顶点的入度
for(auto& edge:g){// 边 b->a
graph[edge[1]].push_back(edge[0]);
indegrees[edge[0]]++;
}
queue<int> q;
// 入度为0的顶点入队列
for(int i=0;i<n;++i){
if(!indegrees[i])q.push(i);
}
// 用cnt统计队列中所有入度为0的点;最后若为有向无环图,则cnt=n;否则存在环的话,cnt<n
int cnt=0;
// 开始bfs,计算所有入度为0的顶点
while(q.size()){
int i=q.front();q.pop();
cnt++;
// 删除从i出发的所有邻接边
for(int j:graph[i]){
if(--indegrees[j]==0)q.push(j);
}
}
return cnt==n;
}
};