1、深度优先遍历——DFS(程序中graph.h是图存储结构的“算法库”中的头文件,详情请单击链接…)
int visited[MAXV];
void DFS(ALGraph *G, int v)
{
ArcNode *p;
int w;
visited[v]=1;
printf("%d ", v);
p=G->adjlist[v].firstarc;
while (p!=NULL)
{
w=p->adjvex;
if (visited[w]==0)
DFS(G,w);
p=p->nextarc;
}
}
int main()
{
int i;
ALGraph *G;
int A[5][5]=
{
{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}
};
ArrayToList(A[0], 5, G);
for(i=0; i<MAXV; i++) visited[i]=0;
printf(" 由2开始深度遍历:");
DFS(G, 2);
printf("\n");
for(i=0; i<MAXV; i++) visited[i]=0;
printf(" 由0开始深度遍历:");
DFS(G, 0);
printf("\n");
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
测试时用的图是,可以使用其他类型的图代替。
2、广度优先遍历——BFS(程序中graph.h是图存储结构的“算法库”中的头文件,详情请单击链接…)
#include <stdio.h>
#include <malloc.h>
#include "graph.h"
void BFS(ALGraph *G, int v)
{
ArcNode *p;
int w,i;
int queue[MAXV],front=0,rear=0;
int visited[MAXV];
for (i=0; i<G->n; i++) visited[i]=0;
printf("%2d",v);
visited[v]=1;
rear=(rear+1)%MAXV;
queue[rear]=v;
while (front!=rear)
{
front=(front+1)%MAXV;
w=queue[front];
p=G->adjlist[w].firstarc;
while (p!=NULL)
{
if (visited[p->adjvex]==0)
{
printf("%2d",p->adjvex);
visited[p->adjvex]=1;
rear=(rear+1)%MAXV;
queue[rear]=p->adjvex;
}
p=p->nextarc;
}
}
printf("\n");
}
int main()
{
ALGraph *G;
int A[5][5]=
{
{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}
};
ArrayToList(A[0], 5, G);
printf(" 由2开始广度遍历:");
BFS(G, 2);
printf(" 由0开始广度遍历:");
BFS(G, 0);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
测试时用的图是,可以使用其他类型的图代替。