图为有向无环图获得拓扑序列算法思想:对未访问结点进行深度优先遍历,如果该顶点不存在未访问的邻接结点,则将结点加入拓扑数组中;重复上述步骤,直到图中不存在未访问的结点,此时拓扑中存放的是逆拓扑序列数组。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_VERTEX_NUM 100
typedef int VertexType;
typedef struct ArcNode {
int adjVex;
struct ArcNode* nextArc;
//int weight;
}ArcNode;
typedef struct VNode {
VertexType data;
ArcNode* firstArc;
}VNode, AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int arcNum, vexNum;
int kind;
}ALGraph;
void createALGraph(ALGraph& G, VertexType* VList, int VListLength, int(*arcList)[2], int arcListLength, int kind) {
for (int i = 1; i <= VListLength; i++) {
G.vertices[i].data = VList[i];
G.vertices[i].firstArc = NULL;
}
for (int i = 0; i < arcListLength; i++) {//注意for循环中i的遍历范围
int v = arcList[i][0];
int w = arcList[i][1];
ArcNode* pnode = (ArcNode*)malloc(sizeof(ArcNode));
pnode->adjVex = w;
pnode->nextArc = G.vertices[v].firstArc;
G.vertices[v].firstArc = pnode;
if (kind == 0) {
pnode = (ArcNode*)malloc(sizeof(ArcNode));
pnode->adjVex = v;
pnode->nextArc = G.vertices[w].firstArc;
G.vertices[w].firstArc = pnode;
}
}
G.arcNum = arcListLength;
G.vexNum = VListLength;
G.kind = kind;
}
int visited1[MAX_VERTEX_NUM] = { 0 };
void visit1(VertexType v) {
printf("%d ", v);
}
void DFS(ALGraph G, VertexType v) {
visit1(v);
visited1[v] = 1;
ArcNode* pnode = G.vertices[v].firstArc;
while (pnode != NULL) {
v = pnode->adjVex;
if (!visited1[v]) {
DFS(G, v);
}
pnode = pnode->nextArc;
}
}
void DFSTrave(ALGraph G) {
for (int index = 1; index <= G.vexNum; index++) {
if (visited1[index] == 0) {
DFS(G, index);
}
}
}
//图为有向无环图
/*获得拓扑序列算法思想:对未访问结点进行深度优先遍历,如果该顶点不存在未访问的邻接结点,则将结点加入拓扑数组中;
重复上述步骤,直到图中不存在未访问的结点,此时拓扑中存放的是逆拓扑序列数组*/
int visited[MAX_VERTEX_NUM] = { 0 };
VertexType path[MAX_VERTEX_NUM] = { 0 };
int pathLength = 0;
void DFSTraves(ALGraph G,VertexType v) {
visited[v] = 1;
ArcNode* pnode = G.vertices[v].firstArc;
while (pnode != NULL) {
int w = pnode->adjVex;//注意啊!!!
if (visited[w]==0) {
DFSTraves(G, w);
}
pnode = pnode->nextArc;
}
path[pathLength++] = v;
}
void print(VertexType* path, int pathlength) {
for (int i = pathLength - 1; i >= 0; i--) {
printf("%d ", path[i]);
}
printf("\n");
}
void getTopologicSort(ALGraph G) {
for (int index = 1; index <= G.vexNum; index++) {
if (!visited[index]) {
DFSTraves(G, index);
}
}
print(path, pathLength);
}
int main() {
int kind, VListLength, arcListLength;
VertexType VList[MAX_VERTEX_NUM];
int arcList[MAX_VERTEX_NUM][2];
scanf("%d", &VListLength);
for (int i = 1; i <= VListLength; i++) {
scanf("%d", &VList[i]);
}
scanf("%d", &arcListLength);
for (int i = 0; i < arcListLength; i++) {
for (int j = 0; j < 2; j++) {
scanf("%d", &arcList[i][j]);
}
}
scanf("%d", &kind);
ALGraph G;
createALGraph(G, VList, VListLength, arcList, arcListLength, kind);
DFSTrave(G);
printf("\n");
getTopologicSort(G);
return 0;
}