#include <iostream>
#include <string>
#define WUXIANG 0
using namespace std;
struct Graph
{
int vertexs; //头节点
int edges; //边
char* pVertex; //用来存放所有的顶点。
int** ppEdge; //用来存储所有的边。
};
//创建图对象
Graph* CreateGraph();
//释放图对象
void destroyGraph(Graph* g);
//初始化图对象
void initGraph(Graph* g);
//获取顶点的图中的下标,如果顶点没有,返回-1;
int _getIdx(Graph* g, char c);
//把图打印出来看一下。
void show(Graph* g);
int main()
{
//创建图对象
Graph* g = CreateGraph();
//初始化图对象
initGraph(g);
//显示图
show(g);
//释放图对象;
destroyGraph(g);
system("pause");
return 0;
}
//初始化图对象
void initGraph(Graph* g)
{
cout << "请输入顶点的个数:\n";
cin >> g->vertexs;
cout << "请输入边条数:\n";
cin >> g->edges;
//开内存:
g->pVertex = new char[g->vertexs + 1];//保存顶点的一维数组
g->ppEdge = new int* [g->vertexs];//保存描述边的二维数组。
for (int i = 0; i < g->vertexs; i++)
{
g->ppEdge[i] = new int[g->vertexs];
memset(g->ppEdge[i], 0, sizeof(int) * g->vertexs);
}
//赋值
cout << "请输入顶点:\n";
cin >> g->pVertex; //自己写就可以这样,如果是给别人就老实用循环
char buff[5] = { 0 };
int srcIdx, dstIdx;
for (int i = 1; i <= g->edges; i++)
{
cout << "请输入第" << i << "条边(A->B):";
cin >> buff;
srcIdx = _getIdx(g, buff[0]);
dstIdx = _getIdx(g, buff[3]);
g->ppEdge[srcIdx][dstIdx] = 1;
//如果是无向图,就加一行代码
#if WUXIANG
g->ppEdge[dstIdx][srcIdx] = 1;
#endif
}
}
//创建图
Graph* CreateGraph()
{
Graph* graph = new Graph;
graph->edges = graph->vertexs = 0;
graph->ppEdge = nullptr;
graph->pVertex = nullptr;
return graph;
}
void destroyGraph(Graph* g)
{
delete[]g->ppEdge;
delete[]g->pVertex;
}
int _getIdx(Graph* g, char c)
{
for (int i = 0; i < g->vertexs; i++)
{
if (c == g->pVertex[i])
return i;
}
return -1;
}
void show(Graph* g)
{
for (int i = 0; i <= g->vertexs; i++)
{
for (int j = 0; j <= g->vertexs; j++)
{
if (i == 0 && j == 0)//左上角空置
cout << " ";
else if (i == 0)
{
cout << g->pVertex[j - 1] << " ";
}
else if (j == 0)
cout << g->pVertex[i - 1] << " ";
else
{
cout << g->ppEdge[i - 1][j - 1] << " ";
}
}
cout << endl;
}
}
11-21
803
01-25
744
05-24
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交