图的应用:拓扑排序

#include <iostream>
using namespace std;

#define MaxVertexNum 100
typedef struct Graph{
	int edge[MaxVertexNum][MaxVertexNum];
	int vexnum;//顶点数 
}; //图的邻接矩阵存储 

//栈
typedef struct SqStack{
	int data[MaxVertexNum];
	int top;
}; 
void InitStack(SqStack &S){
	S.top=-1;
}

bool IsEmpty(SqStack S){
	if(S.top==-1){
		return 1;
	}else{
		return 0;
	}
}

bool Push(SqStack &S,int x){
	if(S.top==MaxVertexNum-1)
		return false;
	S.data[++S.top]=x;
	return true;
}

bool Pop(SqStack &S,int &x){
	if(S.top==-1)
		return false;
	x=S.data[S.top--];
	return true;
}

bool TopologicalSort(Graph G,SqStack &S){
	InitStack(S);
	int i,j;
	int indegree[G.vexnum]={0};
	for(j=0;j<G.vexnum;j++){
		for(i=0;i<G.vexnum;i++){
			if(G.edge[i][j]!=0){
				indegree[j]++;
			}
		}
	}//统计入度
	for(i=0;i<G.vexnum;i++){
		if(indegree[i]==0)
			Push(S,i);
	} 
//	for(i=0;i<G.vexnum;i++){
//		printf("%d ",indegree[i]);
//	} 
	int count=0;
	while(!IsEmpty(S)){
		Pop(S,i);
		printf("%d ",i);
		count++;
		for(j=0;j<G.vexnum;j++){
			if(G.edge[i][j]!=0){
				indegree[j]--;
				if(indegree[j]==0){
					Push(S,j);
				}
			}
		}
	}
	if(count<G.vexnum){
		return false;
	}
	else{
		return true;
	}
}

bool InitGraph(Graph &G){
	G.vexnum=5;
	//0 3 1 0 0
	//0 0 4 5 0
	//0 0 0 6 7
	//0 0 0 0 2
	//0 0 0 0 0
	for(int i=0;i<G.vexnum;i++){
		for(int j=0;j<G.vexnum;j++){
			G.edge[i][j]=0;
		}
	}
	G.edge[0][1]=3;
	G.edge[0][2]=1;
	G.edge[1][2]=4;
	G.edge[1][3]=5;
	G.edge[2][3]=6;
	G.edge[2][4]=7;
	G.edge[3][4]=2;
}

int main() {
	Graph G;
	SqStack S;
	InitGraph(G);
//	for(int i=0;i<G.vexnum;i++){
//		for(int j=0;j<G.vexnum;j++){
//			printf("%d ",G.edge[i][j]);
//		}
//		printf("\n");
//	}
	TopologicalSort(G,S);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值