邻接矩阵代码实现
#include <iostream>
#include <cstdio>
#define INF 327677
const int MaxSize = 105 ;
typedef char InfoTtype ;
using namespace std ;
// 邻接矩阵
typedef struct {
int no ; // 顶点编号
InfoTtype info ;
}VertexType ; // 顶点
typedef struct {
int edges[MaxSize][MaxSize] ;
int n , e ;
VertexType vexs[MaxSize] ;
}MatGraph ;
// 创建邻接矩阵
void CreateMat(MatGraph &g , int A[MaxSize][MaxSize] , int n , int e) {
g.n = n ;
g.e = e ;
for(int i = 0 ; i<g.n ; i ++ ) {
for(int j = 0 ; j<g.n ; j++ ) {
g.edges[i][j] = A[i][j] ;
}
}
}
void DispMat(MatGraph g) {
for (int i=0;i<g.n;i++){
for (int j=0;j<g.n;j++)
if (g.edges[i][j]!=INF)
printf("%4d",g.edges[i][j]);
else
printf("%4s","∞");
printf("\n");
}
}
// 判断是否为对称矩阵
bool issymmetry(MatGraph g){
for(int i = 0 ; i<g.n; i++) {
for(int j = 0 ; j<g.n ; j++ ) {
if(g.edges[i][j] !=g.edges[j][i]) {
return false ;
}
}
}
return true ;
}
int main() {
MatGraph g ;
int A[MaxSize][MaxSize] ;
int n ;
int e ;
cin >> n >>e ;
for(int i = 0 ; i<n ; i++) {
for(int j = 0 ; j<n ; j++)
cin >> A[i][j] ;
}
CreateMat(g,A,n,e) ;
DispMat(g) ;
cout<<issymmetry(g) <<endl;
return 0 ;
}
邻接表代码实现
#include <iostream>
#include <cstdio>
#include <cstdlib>
#define INF 327677
const int MaxSize = 105 ;
typedef char InfoTtype ;
using namespace std ;
typedef struct ANode {
int adjvex ;
struct ANode * nextarc ;
int weight ;
}ArcNode ;// 边结点
typedef struct Vnode {
InfoTtype info ;
int count ;
ArcNode *firstarc ;
} VNode ; // 邻接表 头结点类型
typedef struct {
VNode adjlist[MaxSize] ;
int n ,e ;
}AdjGraph ;
// 创建邻接表
void CreateAdj(AdjGraph *&G , int A[MaxSize][MaxSize] , int n ,int e ) {
int i , j ;
ArcNode * p ;
G =(AdjGraph*)malloc(sizeof(AdjGraph)) ;
for(int i = 0; i<n ; i++) {
G->adjlist[i].firstarc = NULL ; // 给邻接表中所有头结点指针域初始化
}
for(int i = 0 ; i<n ; i++) {
for(int j = n-1 ; j>=0 ; j--) {
if(A[i][j] !=0 && A[i][j] !=INF) {
p = (ArcNode*)malloc(sizeof(ArcNode)) ;
p->adjvex = j ;
p->weight = A[i][j] ;
p->nextarc = G->adjlist[i].firstarc ; // 采用头插法插入结点 P;
G->adjlist[i].firstarc = p ;
}
}
}
G->n = n ;
G->e = n ;
}
void DispAdj(AdjGraph *G) {
ArcNode * p ;
for(int i = 0 ;i<G->n; i++) {
p = G->adjlist[i].firstarc ; //指向顶点 i的头结点
printf("%3d: ",i) ; // 遍历结点 i 所有邻接边
while(p!=NULL) {
printf("%3d[%d] - > " ,p->adjvex , p->weight) ;
p = p->nextarc ;
}
cout<<"^ "<<endl ;
}
}
void Destroyadj(AdjGraph *&G) {
ArcNode *pre , *p ;
for(int i = 0 ; i<G->n ;i++) {
pre = G->adjlist[i].firstarc ;
if(pre !=NULL ) {
p = pre->nextarc ;
while(p !=NULL) {
free(pre) ;
pre = p ;
p = p->nextarc ;
}
free(pre) ;
}
}
free(G) ;
}
int main() {
AdjGraph *G ;
int n , e ;
int A[MaxSize][MaxSize] ;
cin >> n >> e ;
for(int i = 0 ; i<n ; i++) {
for(int j = 0 ; j< n ; j++ ) {
cin >>A[i][j] ;
}
}
CreateAdj(G,A,n,e ) ;
DispAdj(G) ;
Destroyadj(G) ;
return 0 ;
}
/*
测试数据
5
7
0 1 327677 327677 1
1 0 1 1 1
327677 1 0 1 327677
327677 1 1 0 1
1 1 327677 1 0
*/