码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-09-09 11:58:23      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:信息   生成   邻接矩阵   nbsp   getchar   space   include   stream   操作   

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

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

标签:信息   生成   邻接矩阵   nbsp   getchar   space   include   stream   操作   

原文地址:http://www.cnblogs.com/wangchaoyuana/p/7497324.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!