广度优先遍历:
以一个顶点为起点,依次遍历以这个顶点为起始的所有路径
例如:逐个遍历一下所有路径
123
143
145
146
147
17
宽度优先遍历:
以一个顶点为起点,将向下逐层遍历所有未被遍历过的顶点
例如:
访问1
访问237
访问356
但是都只能访问一个连通分量,需要多次去访问完所有的连通分量
#include<stdio.h>
#include<stdlib.h>
#include<SeqQueue.h.h> //线性表头文件
#define ERROR 0
#define OK 1
#define Overflow 2//上溢
#define Underflow 3//下溢
#define NotPresent 4//元素不存在
#define Duplicate 5//有重复元素
typedef int Status;
typedef int ElemType;
typedef struct ENode
{
int adjVex;//任意顶点u的相邻顶点
ElemType w;//边的权值
struct ENode* nextArc;
}ENode;
typedef struct
{
int n;
int e;
ENode **a;
}LGraph;
Status Init(LGraph *lg,int nSize)//初始化
{
int i;
lg->n=nSize;
lg->a=(ENode**)malloc(nSize*sizeof(ENode*));//生成一维指针数组
if(!lg->a)
return OK;
else
{
for(i=0;i<lg->n;i++)
lg->a[i]=NULL;//将指针数组初始化
return OK;
}
}
void Destroy(LGraph *lg)//释放邻接表
{
int i;
ENode *p,*q;
for(i=0;i<lg->n;i++)
{
p=lg->a[i];
q=p;
while(p)
{
p=p->nextArc;
free(q);
q=p;
}
}
free(lg->a);
}
Status Exist (LGraph *lg,int u,int v)//边的搜索
{
ENode* p;
if(u<0||v<0||u>lg->n-1||v>lg->n-1||u==v)
return ERROR;
p=lg->a[u];
while(p&&p->adjVex!=v)
p=p->nextArc;
if(!p)
return ERROR;
else
return OK;
}
Status Insert (LGraph *lg,int u,int v,ElemType w)
{
ENode *p;
if(u<0||v<0||u>lg->n-1||v>lg->n-1||u==v)
return ERROR;
if(Exist(lg,u,v))
return Duplicate;
p=(ENode*)malloc(sizeof(ENode));
p->adjVex=v;
p->w=w;
p->nextArc=lg->a[u];
lg->a[u]=p;
lg->e++;
return OK;
}
Status Remove(LGraph *lg,int u,int v)//边的删除
{
ENode *p,*q;
if(u<0||v<0||u>lg->n-1||v>lg->n-1||u==v)
return ERROR;
p=lg->a[u],q=NULL;
while(p&&p->adjVex!=v)
{
q=p;
p=p->nextArc;
}
if(!p)
return NotPresent;
if(q)
q->nextArc=p->nextArc;
else
lg->a[u]=p->nextArc;
free(p);
lg->e--;
return OK;
}
//深度优先遍历
void DFS(int v,int visited[],LGraph g)
{
ENode *w;
printf("%d",v);
for(w=g.a[v]; w; w=w->nextArc)
{
if(!visited[w->adjVex])
DFS(w->adjVex,visited,g);
}
}
void DFSGraph(LGraph g)
{
int i;
int *visited=(int*)malloc(g.n*sizeof(int));
for(i=0;i<g.n;i++)
visited[i] = 0;
for(i=0;i<g.n;i++)
{
if(!visited[i])
DFS(i,visited,g);
}
free(visited);
}
//宽度优先遍历
void BFS (int v,int visited[],LGraph g)
{
ENode *w;
Queue q;
creat(&q,g.n);
visited[v]=1;
printf("%d",v);
while(!IsEmpty(&q))
{
Front(&q,&v);
DeQueue(&q);
for(w=g.a[v];w;w=w->nextArc)
if(!visited[w->adjVex])
{
visited[w->adjVex]=1;
printf("%d",w->adjVex);
EnQueue(&q,w->adjVex);
}
}
}
void BFSGraph(LGraph g)
{
int i;
int *visited=(int *)malloc(g.n*sizeof(int));
for(i=0;i<g.n;i++)
visited[i]=0;
for(i=0;i<g.n;i++)
if(!visited[i])
BFS(i,visited,g);
free(visited);
}