#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define INF 32767
#define MAVX 100
typedef int InfoType;
typedef int Vertex;
typedef struct
{
int no;
InfoType info;
}VertexType;
typedef struct
{
int edges[MAVX][MAVX];
int vexnum,arcnum;
VertexType vexs[MAVX];
}MGraph;
typedef struct ANode
{
int adjvex;
struct ANode *nextarc;
InfoType info;
}ArcNode;
typedef struct Vnode
{
Vertex data;
ArcNode *firstarc;
}VNode;
typedef VNode AdjList[MAVX];
typedef struct
{
AdjList adjlist;
int n,e;
}ALGraph;
int visited[MAVX];
void MatToList(MGraph g,ALGraph * &G)
{
int i,j,n=g.vexnum;
ArcNode *p;
G=(ALGraph *)malloc(sizeof(ALGraph));
for(i=0;i<n;i++)
G->adjlist[i].firstarc=NULL;
for(i=0;i<n;i++)
for(j=n-1;j>=0;j--)
if(g.edges[i][j]!=0)
{
p=(ArcNode *)malloc(sizeof(ArcNode));
p->adjvex=j;
p->info=g.edges[i][j];
p->nextarc=G->adjlist[i].firstarc;
G->adjlist[i].firstarc=p;
}
G->n=n;
G->e=g.arcnum;
}
void DispMat(MGraph g)
{
int i,j;
for(i=0;i<g.vexnum;i++)
{
for(j=0;j<g.vexnum;j++)
if(g.edges[i][j]==INF)
printf("%3s","∞");
else
printf("%3d",g.edges[i][j]);
printf("\n");
}
}
void DispAdj(ALGraph *G)
{
int i;
ArcNode *p;
for(i=0;i<G->n;i++)
{
p=G->adjlist[i].firstarc;
if(p!=NULL)printf("%3d:",i);
while(p!=NULL)
{
printf("%3d",p->adjvex);
p=p->nextarc;
}
printf("\n");
}
}
void DFS(ALGraph *G,int v)
{
ArcNode *p;
visited[v]=1;
p=G->adjlist[v].firstarc;
while(p!=NULL)
{
if(visited[p->adjvex]==0)
{
printf(" <%d,%d> ",v,p->adjvex);
DFS(G,p->adjvex);
}
p=p->nextarc;
}
}
void BFS(ALGraph *G,int v)
{
ArcNode *p;
int queue[MAVX],front=0,rear=0;
int visited[MAVX];
int w,i;
for(i=0;i<G->n;i++) visited[i]=0;
visited[v]=1;
rear=(rear+1)%MAVX;
queue[rear]=v;
while(front!=rear)
{
front=(front+1)%MAVX;
w=queue[front];
p=G->adjlist[w].firstarc;
while(p!=NULL)
{
if(visited[p->adjvex]==0)
{
printf(" <%d,%d> ",w,p->adjvex);
visited[p->adjvex]=1;
rear=(rear+1)%MAVX;
queue[rear]=p->adjvex;
}
p=p->nextarc;
}
}
printf("\n");
}
int main()
{
int i,j;
MGraph g;
ALGraph *G;
int A[MAVX][11];
g.vexnum=11;
g.arcnum=13;
for(i=0;i<g.vexnum;i++)
for(j=0;j<g.vexnum;j++)
A[i][j]=0;
A[0][3]=1; A[0][2]=1;A[0][1]=1;
A[1][5]=1;A[1][4]=1;
A[2][6]=1;A[2][5]=1;A[2][3]=1;
A[3][7]=1;
A[6][9]=1;A[6][8]=1;A[6][7]=1;
A[7][10]=1;
for(i=0;i<g.vexnum;i++)
for(j=0;j<g.vexnum;j++)
A[j][i]=A[i][j];
for(i=0;i<g.vexnum;i++)
for(j=0;j<g.vexnum;j++)
g.edges[i][j]=A[i][j];
G=(ALGraph *)malloc(sizeof(ALGraph));
MatToList(g,G);
printf("\n图G的邻接表:\n");
DispAdj(G);
printf("\n");
for(i=0;i<g.vexnum;i++)
visited[i]=0;
printf("深度优先生成树:\n");
DFS(G,3);printf("\n");
for(i=0;i<g.vexnum;i++)
visited[i]=0;
printf("广度优先生成树:\n");
BFS(G,3);
printf("\n\n");
return 0;
}
数据结构源码笔记(C语言描述)汇总: