两种遍历方式
1.深度优先遍历
深度优先遍历其实就是树的先根遍历。
例如:我们从顶点v1出发,永远是先访问顶点的左子树,若碰到访问过的顶点就回退到有右子树的顶点。
1.遍历v1,v1有左子树v2,访问v2;
2.遍历v2,v2有左子树v4,访问v4;
3.遍历v4,v4只有子树v8,访问v8;
4.遍历v8,v8只有子树v5 ,访问v5;
5.遍历v5,v5子树已经访问过,回退到没有访问右子树的顶点v1;
6.遍历v3,v3有左子树v6,访问v6;
7.遍历v6,v6无子树,回退到v3;
8.访问v7,遍历v7,v7无子树,回退到v1。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#define max 20
int visited[max];
typedef struct Vertex
{
int vernum, srcnum;
int arc[max][max];
int vertex[max];
}Vertex;
void CreateGraph(Vertex* G)
{
scanf("%d %d", &G->vernum, &G->srcnum);
for (int i = 1; i <= G->vernum; i++)
{
scanf("%d", &G->vertex[i]);
}
for (int i = 1; i <= G->vernum; i++)
{
for (int j = 1; j <= G->srcnum; j++)
{
G->arc[i][j] = 0;
}
}
for (int i = 0; i < G->srcnum; i++)
{
int v1, v2;
scanf("%d %d", &v1, &v2);
G->arc[v1][v2] = 1;
G->arc[v2][v1] = 1;
}
}
void DFS(Vertex* G, int i)
{
visited[i] = 1;
printf("%d ", G->vertex[i]);
for (int j = 1; j <= G->vernum; j++)
{
if (G->arc[i][j] == 1 && !visited[j])
{
DFS(G, j);
}
}
}
void DFStraverse(Vertex* G)
{
for (int i = 1; i <= G->vernum; i++)
{
if (!visited[i])
{
DFS(G, i);
}
}
}
int main()
{
Vertex G;
CreateGraph(&G);
DFStraverse(&G);
return 0;
}
2.广度优先遍历
广度优先遍历其实就是树的层次遍历。
例如:
0-A 1-B 2-C 3-D 4-E 5-F 6-G 7-H
输入输出样例
8 10
ABCDEFGH
0 1 0 2 0 3 0 5
1 6
2 3 2 4
5 7
4 6
4 7
A B C D F G E H
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#define max 20
int visited[max];
typedef struct Vertex
{
int vernum, srcnum;
int arc[max][max];
char vertex[max];
}Vertex;
void CreateGraph(Vertex* G)
{
scanf("%d %d", &G->vernum, &G->srcnum);
scanf("%s", G->vertex);
fflush(stdin);//缓冲区
for (int i = 0; i < G->vernum; i++)
{
for (int j = 0; j < G->vernum; j++)
{
G->arc[i][j] = 0;
}
}
for (int i = 0; i < G->srcnum; i++)
{
int v1, v2;
scanf("%d %d", &v1, &v2);
G->arc[v1][v2] = 1;
G->arc[v2][v1] = 1;
}
}
void BFStraverse(Vertex G)
{
int queue[max] = { 0 };
int rear = 0, front = 0;
int elem;
for (int i = 0; i < G.vernum; i++)
{
if (!visited[i])
{
visited[i] = 1;
queue[rear] = i;
rear = (rear + 1) % max;
while (front < rear)
{
elem = queue[front];
front = (front + 1) % max;
printf("%c ", G.vertex[elem]);
for (int j = 0; j < G.vernum; j++)
{
if (G.arc[elem][j] == 1 && !visited[j])
{
visited[j] = 1;
queue[rear] = j;
rear = (rear + 1) % max;
}
}
}
}
}
}
int main()
{
Vertex G;
CreateGraph(&G);
BFStraverse(G);
return 0;
}