拓扑排序

DAG

单向无环图

拓扑排序

代码

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
//DAG:有向无环图
const int max_n = 30;
vector<int>G[max_n];
queue<int>q;
int n,ind[max_n];
//拓扑排序
bool topologicalSort()
{
	//将所有入度为0的边加入 队列
	for (int i = 0; i < n; i++)
	{
		if (ind[i] == 0)
			q.push(i);
	}
	int cnt = 0;
	while (!q.empty())
	{
		//取出队头 消去与之相连的边并入度-1
		int head = q.front();
		cnt++;
		for (int i = 0; i < G[head].size(); i++)
		{
			ind[G[head][i]]--;
			if (ind[G[head][i]] == 0)
				q.push(i);
		}
		G[head].clear();
	}
	if (cnt == n)
		return true;
	return false;
}

应用

  • 判断一个图有没有环
原文地址:https://www.cnblogs.com/code-fun/p/15236672.html