C++ 图的实现
来源:互联网 发布:重庆大学软件工程学院 编辑:程序博客网 时间:2024/06/03 23:42
//图,已经成功实现#include<iostream>#include<cstdlib>#define MaxNum 20#define MaxValue 128using namespace std;typedef struct Graph//定义图的结构{char Vertex[MaxNum];//节点,字符串类型int GType;//图的类型,0代表无像图,1代表有向图int VertexNum;//节点数量int EdgeNum;//边数量int EdgeWight[MaxNum][MaxNum];//代表图的每条边,及其权值int isTrav[MaxNum];//isTrav数组表示该节点是否遍历过};void CreateGraph(Graph *G)//创建一个图{int i, j, k;int weight;char Estart, Eend;cout << "输入各顶点信息 : " << endl;for (i = 0; i < G->VertexNum; i++){cout << "第 " << i + 1 << " 个定点 " << endl;cin >> G->Vertex[i];}cout << "输入各边顶点及权值 " << endl;for (k = 0; k < G->EdgeNum; k++){cout << "第 " << k + 1 << " 条边 " << endl;cin >> Estart >> Eend >> weight;for (i = 0; G->Vertex[i] != Estart; i++);for (j = 0; G->Vertex[j] != Eend; j++);G->EdgeWight[i][j] = weight;if (G->GType == 0){G->EdgeWight[j][i] = weight;}}}void ClearGraph(Graph *G)//清空{for (int i = 0; i < G->VertexNum; i++)for (int j = 0; j < G->VertexNum; j++)G->EdgeWight[i][j] = MaxValue;}void OutGraph(Graph *G)//输出图的信息,元素+邻接矩阵{//cout << "********************************************" << endl;cout << " ";for (int i = 0; i < G->VertexNum; i++)cout << G->Vertex[i] << " ";cout << endl;// << "********************************************" << endl;for (int i = 0; i < G->VertexNum; i++){cout << G->Vertex[i] << " ";for (int j = 0; j < G->VertexNum; j++){if (G->EdgeWight[i][j] == MaxValue)cout << " N ";elsecout << " " << G->EdgeWight[i][j] << " ";}cout << endl;}}void DeepTraGraphOne(Graph *G, int n)//深度遍历算法,{int i;G->isTrav[n] = 1;cout << G->Vertex[n];for (int i = 0; i < G->VertexNum; i++){if (G->EdgeWight[n][i] != MaxValue&&!G->isTrav[i]) //***{DeepTraGraphOne(G, i);//递归进行深度遍历}}}void DeepTreaGraph(Graph *G)//调用深度遍历算法,实现图的遍历{for (int i = 0; i < G->VertexNum; i++)G->isTrav[i] = 0;cout << "深度优先遍历" << endl;for (int i = 0; i < G->VertexNum; i++){if (!G->isTrav[i]){DeepTraGraphOne(G, i);}}cout << "\n" << endl;}int main(){Graph G;cout << "请输入生成图的类型,0无像,1有像" << endl;cin >> G.GType;cout << "请输入顶点数量" << endl;cin >> G.VertexNum;cout << "请输入边的数量" << endl;cin >> G.EdgeNum;ClearGraph(&G);CreateGraph(&G);cout << "图的邻接矩阵如下" << endl;OutGraph(&G);cout << "深度优先搜索" << endl;DeepTreaGraph(&G);system("pause");return 0;}
//参考自C++常用算法手册
阅读全文
0 0
- [C/C++]汉诺塔的实现
- 图的邻接表存储 c实现
- 图的邻接表存储 c实现
- 图的邻接表存储 c实现
- 图的邻接表存储c实现
- 图的邻接表存储 c实现
- 图的邻接表C实现
- 图的邻接表存储 c实现
- 图的邻接表存储 c实现
- 图的邻接表存储 c实现
- 图的邻接表存储c实现
- 图的邻接表存储 c实现
- 图的邻接矩阵(C语言实现)
- 数据结构-图的简易实现-C
- 堆栈的C实现
- C的类实现
- c库函数的实现
- c实现的urlencode
- Linux信号机制之sigaction结构体浅析
- SpringBoot(1)
- C语言一周学习内容总结
- 【ccf 201709-2】公共钥匙盒
- android 7.0 关闭系统自动旋转
- C++ 图的实现
- 阿里云CentOS7中安装Maven3.5
- redis主从服务器
- 【20171014】python_语言设计(8)面向对象程序设计
- 利用#pragma execution_character_set("utf-8")解决QT中显示中文字乱码
- java 多线程 方法2 使用Runnable接口
- 方法区
- AB1601 IO口反应延时的问题
- Maya Calendar