图:在邻接矩阵上实现拓扑排序(C语言)

拓扑排序:

用于排列事件发生的顺序,也可判断图中是否有环。

代码实现:

#include<stdio.h>
#include<stdlib.h>
#define MaxVexNum 50
#define MaxInt 32767
#define MaxEdgeNum 50
//邻接矩阵
typedef int VertexType;
typedef int EdgeType;
typedef struct AMGraph{
	VertexType vexs[MaxVexNum];//顶点表 
	EdgeType arcs[MaxVexNum][MaxVexNum];//邻接矩阵表 
	int vexnum,edgenum;//顶点数,边数 
}AMGraph; 

void createGraph(AMGraph &g){//创建无向图 
	printf("请输入顶点数:");
	scanf("%d",&g.vexnum);
	printf("\n请输入边数:");
	scanf("%d",&g.edgenum);
	
	//初始化顶点表 
	for(int i=1;i<=g.vexnum;i++){
		g.vexs[i]=i; 
	} 
	for(int i=1;i<=g.vexnum;i++){
		for(int j=1;j<=g.vexnum;j++){
			g.arcs[i][j]=MaxInt;
			if(i==j) g.arcs[i][j]=0;
		}
	} 
	printf("请输入边的信息以及边的权值(顶点是0~n-1)\n");
	for(int i=0;i<g.edgenum;i++){
		int x,y,w;
		scanf("%d%d%d",&x,&y,&w);
		g.arcs[x][y]=w;
		//g.arcs[y][x]=w;
	}
}
void PrintGraph(AMGraph g){
	printf("邻接矩阵为:\n");
	for(int i=1;i<=g.vexnum;i++) {
		printf("  %d",g.vexs[i]);
	}
	printf("\n");
	for(int i=1;i<=g.vexnum;i++){
		printf("%d ",g.vexs[i]);
		for(int j=1;j<=g.vexnum;j++){
			if(g.arcs[i][j]==32767){
				printf("∞ "); 
			}else{
				printf("%d  ",g.arcs[i][j]);
			}	
		}
		printf("\n");
	} 
}
void updateStack(int stack[],int &top,int set[],AMGraph &g){
	for(int i=1;i<=g.vexnum;i++){
		int count=0;
		for(int j=1;j<=g.vexnum;j++){
			if(set[i]==0&&i!=j&&g.arcs[j][i]==MaxInt){
				count++;
			}
		}
		if(count==g.vexnum-1){
			stack[++top]=i;
			set[i]=1;
		}	
	}
} 
//拓扑排序
//用于排列活动发生的先后次序
//也可判断图中是否有环 
void TopSort(AMGraph g,int topsort[]){
	AMGraph temp=g;
	int stack[g.vexnum];
	int top=-1;
	int top1=0;//将拓扑序列存入 
	
	int set[g.vexnum+1];//标记数组 
	for(int i=1;i<=g.vexnum;i++) set[i]=0;
	for(int i=1;i<=g.vexnum;i++){
		int count=0;
		for(int j=1;j<=g.vexnum;j++){
			if(set[i]==0&&i!=j&&g.arcs[j][i]==MaxInt){
				count++;
			}
		}
		if(count==g.vexnum-1){
			stack[++top]=i;
			set[i]=1;
		}	
	}
	printf("拓扑排序序列为:"); 
	
	while(top!=-1){
		int e=stack[top--];
		printf("%d  ",e);
		topsort[++top1]=e;
		//更新
		for(int i=1;i <= temp.vexnum;i++){
		    if(i!=e)	temp.arcs[e][i]=MaxInt;
		} 
		//更新栈
		updateStack(stack,top,set,temp); 	 
	}
	
	
}
void KeyPath(){
	
} 
int main(){
	AMGraph g;
	createGraph(g);
	PrintGraph(g);
	int topsort[g.vexnum+1];

	TopSort(g,topsort);
	

	
	
	 
} 

代码运行截图:

发布了90 篇原创文章 · 获赞 36 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_37716512/article/details/104235037
今日推荐