# C++无向图的邻接矩阵

0

```这是最基本的简历无向图邻接矩阵表示的代码：#include<iostream>
using namespace std;
typedef char VertexType;
typedef int EdgeType;
#define MAXVEX 100
#define INFINITY 65535
typedef struct
{
VertexType vexs[MAXVEX];
EdgeType arc[MAXVEX][MAXVEX];
int numVertexes,numEdges;
}MGraph;

int main(MGraph *G)
{
int i,j,k,w;
cout<<"输入定点数和边数："<<endl;
cin>>G->numVertexes>>G->numEdges;
for(i=0;i<G->numVertexes;++i)
cin>>G->vexs[i];
for(i=0;i<G->numVertexes;++i)
for(j=0;j<G->numVertexes;++j)
G->arc[i][j]=INFINITY; //邻接矩阵初始化
for(k=0;k<G->numEdges;++k)
{
cout<<"输入边（vi,vj）上的下标i、下标j和权值w:"<<endl;
cin>>i>>j;
G->arc[i][j]=w;
G->arc[j][i]=G->arc[i][j];//由于是无向图，矩阵对称
}
for(i=0;i<G->numVertexes;++i)
for(j=0;j<G->numVertexes;++j)
{cout<<G->arc[i][j];}
return 0;
} ```

1
```#include<iostream>
using namespace std;
typedef char VertexType;
typedef int EdgeType;
#define MAXVEX 100
#define INFINITY 65535
typedef struct
{
VertexType vexs[MAXVEX];
EdgeType arc[MAXVEX][MAXVEX];
int numVertexes,numEdges;
}MGraph;

int main()
{
MGraph *G=new MGraph;
int i,j,k,w;
cout<<"输入定点数和边数："<<endl;
cin>>G->numVertexes>>G->numEdges;
for(i=0;i<G->numVertexes;++i)
cin>>G->vexs[i];
for(i=0;i<G->numVertexes;++i)
for(j=0;j<G->numVertexes;++j)
G->arc[i][j]=INFINITY; //邻接矩阵初始化
for(k=0;k<G->numEdges;++k)
{
cout<<"输入边（vi,vj）上的下标i、下标j和权值w:"<<endl;
cin>>i>>j;
G->arc[i][j]=w;
G->arc[j][i]=G->arc[i][j];//由于是无向图，矩阵对称
}
for(i=0;i<G->numVertexes;++i)
for(j=0;j<G->numVertexes;++j)
{cout<<G->arc[i][j];}
return 0;
}```

@响O(∩_∩)O:

```for(i=0;i<G->numVertexes;++i)
for(j=0;j<G->numVertexes;++j)
{cout<<G->arc[i][j];}这个是打印邻接矩阵的所有边，初始化时将其初始为```
`#define INFINITY 65535`

@星空雾雨: 嗯，明白了，非常感谢您的耐心讲解！

您需要登录以后才能回答，未注册用户请先注册