数据结构之邻接矩阵存图

本身邻接矩阵就是一个简单的二维数组,但是考虑到顶点的下标标号可能不是从1开始到的N结束的。所以用如下算法。当然你也可以离散化一下坐标再普通存图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
typedef struct Matrix{
int vertex[101];
int M[101][101];
}Graph;
int locate(Graph G, int x,int n)
{
for(int i = 1; i <= n; ++i)
{
if(G.vertex[i] == x)
{
return i;
}
}
}
void create(Graph &G,int n,int arcnum)
{
int a,b,w;
for(int i = 1; i <= n; ++i)
{
cin >> G.vertex[i];
}
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
if(i != j)
G.M[i][j] = G.M[j][i] = inf;
for(int i = 1; i <= arcnum; ++i)
{
cin >> a >> b >> w;
int A = locate(G,a,n);
int B = locate(G,b,n);
G.M[A][B] = G.M[B][A] = w;
}
}
int main()
{
Graph G;
int n,arcnum;
cin >> n;
cin >> arcnum;
create(G, n, arcnum);
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= n ; ++j)
{
printf("%d%c",G.M[i][j],j==n?'\n':' ');
}
}
}