zoukankan      html  css  js  c++  java
  • 【数据结构】图结构操作示例

    #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<<"输入图中各顶点信息
    ";
    	for(i=0 ; i<GM->vertexNum; i++){
    		getchar();
    		cout<<"第"<<i+1<<"个顶点:";
    		cin>>GM->vertex[i]; 
    	}
    	cout<<"输入构成个边的顶点以及权值:
    ";
    	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<<"
    ";
    	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<<"	Z";
    			}
    			else{
    				cout<<GM->edgeWeight[i][j];
    			}
    		}
    		cout<<"
    ";
    	} 
    }
    
    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<<"该图的邻接矩阵如下:
    ";
    	OutGraph(&GM);
    	DeepTraGraph(&GM);
    	return 0;
    } 
    

      

  • 相关阅读:
    117. 填充每个节点的下一个右侧节点指针 II
    116. 填充每个节点的下一个右侧节点指针
    114. 二叉树展开为链表
    9.5 NLP slide: 第二课 语言模型
    165. 比较版本号
    143. 重排链表
    147. 对链表进行插入
    127. 单词接龙
    129. 求根到叶子节点数字之和
    95. 不同的二叉搜索树 II 递归
  • 原文地址:https://www.cnblogs.com/dragonir/p/5027071.html
Copyright © 2011-2022 走看看