邻接表存图
存储结构
#define MaxSize 10
typedef char DataType;
typedef struct EdgeNode{
int adjvex;
struct EdgeNode *next;
} EdgeNode;
typedef struct{
DataType vertex;
EdgeNode *first;
} vertexNode;
typedef struct{
vertexNode adjlist[MaxSize];
int vertexNum, edgeNum;
} ALGraph;
有向图邻接表的建立
void CreateGraph(ALGraph *G, DataType a[], int n, int m){
G->vertexNum=n, G->edgeNum=m;
for(int i=0; i<n; i++){
G->adjlist[i].vertex=a[i];
G->adjlist[i].first=NULL;
}
for(int i=0; i<m; i++){
int x, y;
scanf("%d%d", &x, &y);
EdgeNode *s=(EdgeNode*)malloc(sizeof(EdgeNode));
s->adjvex=y;
s->next=G->adjlist[x].first;
G->adjlist[x].first=s;
}
}
图的销毁
void DestroyGraph(ALGraph *G){
for(int i=0; i<G->vertexNum; i++){
EdgeNode *p, *q;
p=q=G->adjlist[i].first;
while(p != NULL){
p=p->next;
free(q);
q=p;
}
}
}
深度优先遍历
void dfs(ALGraph *G, int r){
printf("%c ", G->adjlist[r].vertex);
st[r]=1;
EdgeNode *p=G->adjlist[r].first;
while(p != NULL){
int u=p->adjvex;
if(st[u]==0) dfs(G, u);
p=p->next;
}
}
广度优先遍历
void bfs(ALGraph *G, int r){
int Q[MaxSize];
int front=-1, rear=-1;
printf("%c ", G->adjlist[r].vertex);
st[r]=1; Q[++rear]=r;
while(front != rear){
int u=Q[front ++];
EdgeNode *p=G->adjlist[u].first;
while(p != NULL){
int v=p->adjvex;
if(st[v]==0){
printf("%c ", G->adjlist[v].vertex);
st[v]=1; Q[++rear]=v;
}
p=p->next;
}
}
}