一.测试用图
二.拓扑排序
void toposort(graph g) {//注意,拓扑排序中要把邻接矩阵中没有边的位置置为0(为了统计入度)
size_t N = g.cost.size();
vector<int> InDegree(N, 0);//统计入度,每个顶点的入度初始化为0
for (size_t col = 0;col < N;++col) {
for (size_t row = 0;row < N;++row)
InDegree[col] += g.cost[row][col];
}
queue<int> q;
for (size_t i = 0;i < InDegree.size();++i) {
if (InDegree[i] == 0)//入度为0的进队列,此处也可以换成堆栈
q.push(i);
}
while (!q.empty()) {
int cur = q.front();
q.pop();
cout << g.vertex[cur] << " ";
for (size_t i = 0;i < N;++i) {
if (g.cost[cur][i] != 0) {//如果存在边
--InDegree[i];//切除上一个入度为0的顶点,与其相连的点的入度减少一
if (InDegree[i] == 0)
q.push(i);
}
}
}
}
测试:
//拓扑排序中要把没有边的位置初始化为0,因为要计算入度
vector<vector<int>> tp(5, vector<int>(5, 0));
tp[0][1] = 1;
tp[0][3] = 1;
tp[1][2] = 1;
tp[1][3] = 1;
tp[2][4] = 1;
tp[3][2] = 1;
tp[3][4] = 1;
graph g;
g.cost = tp;
g.vertex = { "1","2","3","4","5" };
toposort(g);
测试结果: