PS.更多数据结构知识详见:
八大数据结构
图的数据结构
const int MAXVEX = 100;
typedef char VertexType;
typedef int EdgeType;
struct Graph
{
VertexType vexs[MAXVEX];
EdgeType arc[MAXVEX][MAXVEX];
int numVertexes, numEdges;
};
邻接矩阵构建图
void CreateGraph(Graph& G)
{
cout << "输入顶点数和边数 :" << endl;
cin >> G.numVertexes >> G.numEdges;
cout << "输入顶点的信息 :" << endl;
for (int i = 0; i < G.numVertexes; i++)
cin >> G.vexs[i];
for (int i = 0; i < G.numVertexes; i++)
{
for (int j = 0; j < G.numEdges; j++)
G.arc[i][j] = -1;
}
cout << "输入边的信息 :" << endl;
int i, j, w;
for (int k = 0; k < G.numEdges; k++)
{
cin >> i >> j >> w;
G.arc[i][j] = w;
G.arc[i][j] = w;
}
}
图的深度优先遍历
bool visited[MAXVEX];
void DFS(Graph G, int i)
{
visited[i] = true;
cout << G.vexs[i] << " ";
for (int j = 0; j < G.numVertexes; j++)
{
if (G.arc[i][j] != -1 && visited[j] == false)
DFS(G, j);
}
}
void DFSTraverse(Graph G)
{
for (int i = 0; i < MAXVEX; i++)
visited[i] = false;
for (int i = 0; i < G.numVertexes; i++)
{
if (visited[i] == false)
DFS(G, i);
}
}
图的广度优先遍历
void BFSTraverse(Graph G)
{
for (int i = 0; i < MAXVEX; i++)
visited[i] = false;
queue<int> que;
for (int i = 0; i < G.numVertexes; i++)
{
if (visited[i] == false)
{
que.push(i);
visited[i] = true;
while (!que.empty())
{
int cur = que.front();
for (int j = 0; j < G.numVertexes; j++)
{
if (G.arc[cur][j] != -1 && !visited[j])
{
que.push(j);
visited[j] = true;
}
}
cout << G.vexs[cur] << " ";
que.pop();
}
}
}
}
测试
void testGraph()
{
Graph G;
CreateGraph(G);
cout << "深度优先遍历的结果 :" << endl;
DFSTraverse(G);
cout << endl << endl;
cout << "广度优先遍历的结果 :" << endl;
BFSTraverse(G);
}
结果