【數據結構】圖結構操做示例

#include<iostream>
#include<cstring>
#include<queue>
#include<stack>
#include<cstdio>

#define MAXNUM 20
#define MAXVALUE 65535
using namespace std;

typedef struct{
	//char vertex[MAXNUM][MAXNUM];
	char vertex[MAXNUM][MAXNUM];
	int GType;
	int vertexNum;
	int edgeNum;
	int edgeWeight[MAXNUM][MAXNUM];
	int travel[MAXNUM];
}GraphMatrix;

void CreatGraph(GraphMatrix *GM){  //建立鄰接矩陣 
	int i,j,k;
	int weight;
	char Estart, Eend;
	cout<<"輸入圖中各頂點信息\n";
	for(i=0 ; i<GM->vertexNum; i++){
		getchar();
		cout<<"第"<<i+1<<"個頂點:";
		cin>>GM->vertex[i]; 
	}
	cout<<"輸入構成個邊的頂點以及權值:\n";
	for(k=0; k<GM->edgeNum; k++){
		getchar();
		cout<<"第"<<k+1<<"條邊:";
		cin>>Estart>>Eend>>weight;
		for(i=0; &Estart!=GM->vertex[i]; i++);  //在已有的頂點中查找實點 
		for(j=0; &Eend!=GM->vertex[j]; j++);    //在已有的頂點中查找終點 
		GM->edgeWeight[i][j]= weight;
		if(GM->GType==0){
			GM->edgeWeight[i][j]=weight;
		} 
	} 
}

void ClearGraph(GraphMatrix * GM){
	int i,j;
	for(i=0; i<GM->vertexNum; i++){
		for(j=0; j<GM->vertexNum; j++){
			GM->edgeWeight[i][j]==MAXVALUE;
		}
	}
}

void OutGraph(GraphMatrix * GM){
	int i,j ;
	for(j=0 ; j<GM->vertexNum; j++){
		cout<<GM->vertex[j]; 
	} 
	cout<<"\n";
	for(i=0 ; i<GM->vertexNum; i++){
		cout<<GM->vertex[i];
		for(j=0; j<GM->vertexNum; j++){
			if(GM->edgeWeight[i][j]==MAXVALUE){
				cout<<"\tZ";
			}
			else{
				cout<<GM->edgeWeight[i][j];
			}
		}
		cout<<"\n";
	} 
}

void DeepTraOne(GraphMatrix * GM  , int n){
	int i;
	GM->travel[n]=1;
	cout<<GM->vertex[n];
	for(i=0; i<GM->vertexNum; i++){
		if(GM->edgeWeight[n][i]!=MAXVALUE&&!GM->travel[n]){
			DeepTraOne(GM,i);
		}
	}
}

void DeepTraGraph(GraphMatrix * GM){
	int i ;
	for(i=0; i<GM->vertexNum; i++){
		GM->travel[i]=0;
	}
	cout<<"深度優先遍歷結點:";
	for(i=0; i<GM->vertexNum; i++){
		if(!GM->travel[i]){
			DeepTraOne(GM, i);
		}
	}
	cout<<endl;
}

int main(){
	GraphMatrix GM;
	cout<<"輸入生成圖的類型: ";
	cin>>GM.GType;
	cout<<"輸入圖的頂點數量:";
	cin>>GM.vertexNum;
	cout<<"輸入圖的邊數量: ";
	cin>>GM.edgeNum;
	ClearGraph(&GM);
	CreatGraph(&GM);
	cout<<"該圖的鄰接矩陣以下:\n";
	OutGraph(&GM);
	DeepTraGraph(&GM);
	return 0;
} 
相關文章
相關標籤/搜索