【数据结构】图结构操作示例

#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;
} 

  

posted @ 2015-12-07 18:38  Dragonir  阅读(590)  评论(0编辑  收藏  举报