要表示一个图G=(V,E),有两种标准的表示方法,即邻接表和邻接矩阵。这两种表示法既可用于有向图,也可用于无向图。通常采用邻接表表示法,因为用这种方法表示稀疏图(图中边数远小于点个数)比较紧凑。但当遇到稠密图(|E|接近于|V|^2)或必须很快判别两个给定顶点手否存在连接边时,
通常采用邻接矩阵表示法,例如求最短路径算法中,就采用邻接矩阵表示。
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#define MAXN 50
//邻接矩阵
int edge[MAXN][MAXN];
int other(){
int i,j;
int n,m;
int u,v;
int od,id;
while(1){
scanf("%d%d",&n,&m);
if(n==0 && m==0){
printf("没有输入边和点的个数
");
break;
}
memset(edge, 0, sizeof(edge));
for(i=0;i<m;i++){
scanf("%d%d",&u,&v);
edge[u-1][v-1] = 1;
}
for(i=0;i<n;i++){
od = 0;
for(j=0;j<n;j++){
od += edge[i][j];
}
if(i==0){
printf("%d",od);
}
else{
printf(" %d",od);
}
}
printf("
");
for(i=0;i<n;i++){
id =0;
for(j=0;j<n;j++){
id += edge[j][i];
}
if(i==0){
printf("%d",id);
}
else{
printf(" %d",id);
}
}
printf("
");
}
return 0;
}
//邻接表
typedef struct arcnode * arc;
typedef struct vnode * vno;
typedef struct lgraph * lgr;
struct arcnode{
int id;
arc next_arcnode;
};
struct vnode{
int id;
arc inhead;
arc outhead;
};
struct lgraph{
struct vnode vnodes[MAXN];
int vex=0;
int arc=0;
};
lgr create_null_lg(){
}
lgr create_lg(lgr lg){
int i;
int n,m;
arc p=NULL;
for(i=0;i<lg->vex;i++){
lg->vnodes[i].inhead = lg->vnodes[i].outhead = NULL;
}
for(i=0;i<lg->arc;i++){
scanf("%d%d",&n,&m);
n--;
m--;
p = (arc)malloc(sizeof(struct arcnode));
p->id = m;
p->next_arcnode = lg->vnodes[n].inhead;
lg->vnodes[n].inhead = p;
p = (arc)malloc(sizeof(struct arcnode));
p->id = n;
p->next_arcnode = lg->vnodes[m].outhead;
lg->vnodes[m].outhead = p;
}
return lg;
}
void free_lg(lgr lg){
int i;
arc p;
for(i=0;i<lg->vex;i++){
p = lg->vnodes[i].inhead;
while(p!=NULL){
lg->vnodes[i].inhead = p->next_arcnode;
free(p);
p = lg->vnodes[i].inhead;
}
p = lg->vnodes[i].outhead;
while(p!=NULL){
lg->vnodes[i].outhead = p->next_arcnode;
free(p);
p = lg->vnodes[i].outhead;
}
}
}
int main(){
int i;
int m,n;
int id,od;
arc p;
struct lgraph lg;
while(1){
printf("输入多少条边和点");
scanf("%d%d",&(lg.vex),&(lg.arc));
if(lg.vex==0){
break;
}
create_lg(&lg);
for(i=0;i<lg.vex;i++){
od =0;
p = lg.vnodes[i].inhead;
while(p!=NULL){
od ++;
p = p->next_arcnode;
}
if(i==0){
printf("%d",od);
}
else{
printf(" %d",od);
}
}
printf("
");
for(i=0;i<lg.vex;i++){
id =0;
p = lg.vnodes[i].outhead;
while(p!=NULL){
id ++;
p = p->next_arcnode;
}
if(i==0){
printf("%d",id);
}
else{
printf(" %d",id);
}
}
printf("
");
free_lg(&lg);
}
return 0;
}