图的邻接矩阵(Adjacency Matrix)表示是采用二维数组的方式。通过邻接矩阵可以立刻看出两顶点之间是否存在一条边,只需要检查邻接矩阵重行i和列j是否是非零值。对于无向图,邻接矩阵是对称的。下图是摘自《算法:C语言实现》
#include <iostream>
using namespace std;
const int VERTEX_NUM = 20; // 顶点的最大数
typedef int graph_weight_t; // 边的权值类型 可以为 int float double
typedef struct SArc
{
graph_weight_t Weight; // 权值
}AdjMatrix[VERTEX_NUM][VERTEX_NUM]; // 邻接矩阵
typedef struct SGraph
{
int iVertexNum; // 顶点数
int iArcNum; // 边数
int aVertex[VERTEX_NUM]; // 顶点向量
AdjMatrix mArcs; //邻接矩阵
}Graph;
void IintGraph(Graph &graph)
{
//graph = (pGraph)malloc(sizeof(Graph));
graph.iVertexNum = 0;
graph.iArcNum = 0;
for(int i = 0; i < VERTEX_NUM; i++)
graph.aVertex[i] = 0;
for(int i = 0; i < VERTEX_NUM; i ++)
for(int j= 0; j < VERTEX_NUM; j ++)
graph.mArcs[i][j].Weight = 0;
}
void Add_Vertex(Graph &graph)
{
cout << "Add Vertex" << endl;
cout << "Input vertex number:";
cin >> graph.iVertexNum;
cout << "Input vertex value:";
for(int i = 0; i < graph.iVertexNum; i ++)
cin >> graph.aVertex[i];
}
int Locat_vertex(Graph &graph, int vertex)
{
for(int i = 0; i < graph.iVertexNum; i ++)
{
if(graph.aVertex[i] == vertex)
return i;
}
return -1;
}
void Add_Arcs(Graph &graph)
{
cout << "Add Arcs" << endl;
cout << "input arcs numbers:";
cin >> graph.iArcNum;
int iFirst = 0;
int iSecond = 0;
int iRow = 0;
int iCol = 0;
graph_weight_t iWeight = 0;
for(int i = 0; i < graph.iArcNum; i ++)
{
cout << "Input two Arc and Weight(ex. 1 2 32)" << endl;
cin >> iFirst >> iSecond >> iWeight;
iRow = Locat_vertex(graph, iFirst);
iCol = Locat_vertex(graph, iSecond);
graph.mArcs[iRow][iCol].Weight = iWeight;
graph.mArcs[iCol][iRow].Weight = iWeight;
}
}
void Creat_Graph(Graph &graph)
{
cout << "Creat Graph" << endl;
Add_Vertex(graph);
Add_Arcs(graph);
}
void Show_Graph(Graph &graph)
{
cout << "show the graph represented by adjmatrix "<<endl;
for(int row = 0; row < graph.iVertexNum; row ++)
{
for(int col =0; col < graph.iVertexNum; col ++)
{
cout << graph.mArcs[row][col].Weight << "\t";
}
cout << endl;
}
}
int main()
{
Graph graph;
IintGraph(graph);
Creat_Graph(graph);
Show_Graph(graph);
}
原文地址:http://blog.csdn.net/zwhlxl/article/details/45059357