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++常用算法手册

原创粉丝点击