- 图的基础概念讲解
此博客介绍比较全面 - 例子及代码
邻接矩阵:有向图和无向图都可以存储
其邻接矩阵如下:无向图的邻接矩阵关于主对角线对称
代码:
#include<bits/stdc++.h>
using namespace std;
#define maxn 100
typedef struct GNode
{
int edgeNum; //边数
int vetexNum; //顶点数
int G[maxn][maxn]; //邻接矩阵
}*pGraph;
typedef struct ENode
{
int start;
int end;
int weight;
}*pEdge;
pGraph InitGraph(int vetexNum)
{
pGraph Graph;
Graph = (pGraph)malloc(sizeof(GNode));
Graph->vetexNum = vetexNum;
Graph->edgeNum = 0;
//编号是从0到vetexNum-1
for(int i = 0; i < Graph->vetexNum; ++i)
{
for(int j = 0; j < Graph->vetexNum; ++j)
{
Graph->G[i][j] = 0;
}
}
return Graph;
}
void InsertEdge(pGraph Graph,pEdge E)
{
Graph->G[E->start][E->end] = E->weight;
//无向图需要加一条反向边
Graph->G[E->end][E->start] = E->weight;
}
pGraph CreateGraph()
{
pGraph Graph;
pEdge E;
int nv;
printf("Please input VetexNum:");
scanf("%d",&nv);
Graph = InitGraph(nv);
printf("Please input EdgeNum:");
scanf("%d",&(Graph->edgeNum));
if(Graph->edgeNum != 0)
{
E = (pEdge)malloc(sizeof(ENode));
printf("Please input start,end,weight:\n");
for(int i = 0; i < Graph->edgeNum; ++i)
{
scanf("%d %d %d",&E->start,&E->end,&E->weight); //无向图默认是1
InsertEdge(Graph,E);
}
}
return Graph;
}
void Print(pGraph Graph)
{
printf("matrix:\n");
for(int i = 0; i < Graph->edgeNum; ++i){
for(int j = 0; j < Graph->edgeNum; ++j){
printf("%d ",Graph->G[i][j]);
}
printf("\n");
}
}
int main()
{
pGraph Graph;
Graph = CreateGraph();
Print(Graph);
return 0;
}
/*
5
6
0 1 1
0 2 1
0 3 1
1 3 1
1 4 1
2 3 1
*/
/*
//简易版
void Build()
{
scanf("%d",&vetexnum);
for(int i = 0; i < vertexnum; ++i)
for(int j = 0; j < vertexnum; ++j)
Graph[i][j] = 0;
scanf("%d",&edgenum);
for(int i = 0; i < edgenum; ++i)
{
scanf("%d%d%d",&start, &end, &weight);
Graph[start][end] = weight;
Graph[end][start] = weight;
}
}
*/
结果