主要运用:
1.图的邻接矩阵和邻接表存储结构;
2.图的深度优先遍历和广度优先遍历算法,复习栈和队列的应用;
3.图的最小生成树、最短路径等应用及算法思想。
实现功能:以邻接矩阵或邻接表方式建立无向图,并分别利用深度优先遍历和广度优先遍历方法输出各结点元素。
#include <iostream>
typedef int ElemType;
#define MaxSize 100
#define MAXVEX 100
#define INF 32767
typedef char VertexType[10];
int visited[MAXVEX];
using namespace std;
typedef struct edgenode
{
int adjvex;
int weight;
struct edgenode * nextarc;
}ArcNode;
typedef struct vexnode
{
VertexType data;
ArcNode *firstarc;
}VHeadNode;
typedef struct
{
int n,e;
VHeadNode adjlist[MAXVEX];
}AdjGraph;
void CreateGraph(AdjGraph *&G,int A[][MAXVEX],int n,int e)
{
int i,j;
ArcNode *p;
G=(AdjGraph *)malloc(sizeof(AdjGraph));
G->n=n;G->e=e;
for(i=0;i<G->n;i++)
G->adjlist[i].firstarc=NULL;
for(i=0;i<G->n;i++)
for(j=G->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;
G->adjlist[i].firstarc=p;
}
}
void DestroyGraph(AdjGraph *&G)
{
int i;
ArcNode *pre,*p;
for (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);
}
void DispGraph(AdjGraph *G)
{
ArcNode * p;
int i;
for(i=0;i<G->n;i++)
{
printf("[%2d]",i);
p=G->adjlist[i].firstarc;
if(p!=NULL)
printf("→");
while(p!=NULL)
{
printf("%d(%d)",p->adjvex,p->weight);
p=p->nextarc;
}
printf("\n");
}
}
void DFS(AdjGraph *G,int v)
{
int w;
ArcNode *p;
printf("%d",v);
visited[v]=1;
p=G->adjlist[v].firstarc;
while(p!=NULL)
{
w=p->adjvex;
if(visited[w]==0)
DFS(G,w);
p=p->nextarc;
}
}
void BFS(AdjGraph *G,int v)
{
int i,w,visited[MAXVEX];
int Qu[MAXVEX],front=0,rear=0;
ArcNode *p;
for (i=0;i<G->n;i++) visited[i]=0;
printf("%d",v);
visited[v]=1;
rear=(rear=1)%MAXVEX;
Qu[rear]=v;
while (front!=rear)
{
front=(front+1)%MAXVEX;
w=Qu[front];
p=G->adjlist[w].firstarc;
while(p!=NULL)
{
if(visited[p->adjvex]==0)
{
printf("%d",p->adjvex);
visited[p->adjvex]=1;
rear=(rear+1)%MAXVEX;
Qu[rear]=p->adjvex;
}
p=p->nextarc;
}
}
}
int main()
{
AdjGraph *G;
int n=5,e=6,i;
int A[MAXVEX][MAXVEX]={{0,1,0,1,0},{1,0,1,0,0},{0,1,0,1,1},{1,0,1,0,1},{0,0,1,1,0}};
CreateGraph(G,A,n,e);
printf("邻接表G:\n");
DispGraph(G);
for(i=0;i<G->n;i++) visited[i]=0;
printf("各种遍历序列:\n");
printf("DFS:");DFS(G,0);printf("\n");
printf("BFS:");BFS(G,0);printf("\n");
DestroyGraph(G);
}
实现界面:
实现