程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 拓撲排序---(圖的領接表實現)

拓撲排序---(圖的領接表實現)

編輯:C++入門知識

#include<iostream>
using namespace std;

#define MAX_NODE 30
#define MAX_INFO 10
bool isOutput[MAX_NODE];   //記錄該節點有沒有輸出
struct ListNode
{
	ListNode(){next=NULL;}
	int position;				
	ListNode* next;				
};
struct VertexNode
{
	VertexNode()
	{
		head=NULL;
		inDegree=0;
	}
	int currentPosition;		//當前節點在圖存儲結構中數組的位置
	int inDegree;				//該節點的入度
	char info[MAX_INFO];		//該節點的信息
	ListNode* head;				//該節點相鄰節點的第一個節點
};
struct Graphic
{
	int vertex,edge;
	VertexNode vers[MAX_NODE];
};

void createGraphic(Graphic& graphic)
{
	

	cout<<"請輸入節點數和邊數: ";
	cin>>graphic.vertex>>graphic.edge;

	cout<<"請輸入節點信息:"<<endl;
	int i;
	for(i=0;i<graphic.vertex;i++)
	{
		cout<<"請輸入第"<<i<<"個節點信息:";
		cin>>graphic.vers[i].info;
		
	}

	cout<<"請輸入邊信息:"<<endl;

	int first=0;
	int second=0;
	for(i=0;i<graphic.edge;i++)
	{
		cout<<"請輸入第"<<i<<"條邊信息:";
		cin>>first>>second;
		ListNode* temp=new ListNode;
		temp->position=second;
		temp->next=graphic.vers[first].head;
		graphic.vers[first].head=temp;
		++graphic.vers[second].inDegree;		
	}

	for(i=0;i<graphic.vertex;i++)
	{
		isOutput[i]=false;
	}

	for(i=0;i<graphic.vertex;i++)
	{
		graphic.vers[i].currentPosition=i;
	}
}

void printGraphic(Graphic graphic)
{
	int i;
	ListNode* temp=NULL;
	for(i=0;i<graphic.vertex;i++)
	{
		cout<<graphic.vers[i].info<<"--->";
		temp=graphic.vers[i].head;
		if(!temp)
		{
			cout<<"NULL";
		}
		while(temp)
		{
			cout<<temp->position<<" ";
			temp=temp->next;
		}
		cout<<endl;
	}

	for(i=0;i<graphic.vertex;i++)
	{
		cout<<"節點"<<i<<"的入度:";
		cout<<graphic.vers[i].inDegree<<endl;
	}
	cout<<endl;
}
VertexNode* findZeroInDegreeNode(Graphic& graphic)
{
	int i;
	for(i=0;i<graphic.vertex;i++)
	{
		if(graphic.vers[i].inDegree==0)
		{
			graphic.vers[i].inDegree=1;
			return &graphic.vers[i];			
		}
	}
	return NULL;
}

void TopologicalSortForVertex(Graphic& graphic,int position)
{
	ListNode* head=graphic.vers[position].head;
	while(head)
	{
		if(!isOutput[head->position])
		{
			cout<<graphic.vers[head->position].info<<" ";
			isOutput[head->position]=true;
		}
		TopologicalSortForVertex(graphic,head->position);
		head=head->next;
	}
}
void TopologicalSort(Graphic& graphic)
{
	VertexNode* zeroNode=findZeroInDegreeNode(graphic);
	if(!zeroNode)
		return;
	if(!isOutput[zeroNode->currentPosition])
	{
		cout<<zeroNode->info<<" ";
		isOutput[zeroNode->currentPosition]=true;
	}
	
	TopologicalSortForVertex(graphic,zeroNode->currentPosition);
	TopologicalSort(graphic);
}
void main()
{
	Graphic myGraphic;
	createGraphic(myGraphic);
	printGraphic(myGraphic);
	TopologicalSort(myGraphic);
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved