您的位置:首页 > 理论基础 > 数据结构算法

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

2015-12-07 18:38 471 查看
#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
=1;
cout<<GM->vertex
;
for(i=0; i<GM->vertexNum; i++){
if(GM->edgeWeight
[i]!=MAXVALUE&&!GM->travel
){
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;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: