1. 图(graph)的基本概念:
(1). 图由顶点(vertex)和边组成(edge)。
(2). 图又分为有向图(directed graphs)和无向图(undirected graphs)。
2. 图的表示方法:
图的表示方法有两种,邻接表(adjacency lists)和邻接矩阵(adjacency matrix)。图的示例如下:
上图为无向图(来自算法导论图22.1)及邻接表和邻接矩阵表示。
上图为有向图(来自算法导论图22.2)。
图的邻接表和邻接矩阵的c语言定义如下:
邻接表定义为:
#define N 6
struct node {
int adj_vertex;
//int weight; /* For network */
struct node *next;
};
struct adj_list {
int vertex;
struct node *first;
};
struct adj_list lists[N];
由上面可知,邻接表由一个顶点和一条链表组成。
邻接矩阵定义为:
#define N 6
struct adj_matrix {
int vertex[N];
int edge[N][N];
};
邻接矩阵则由一个一维数组和一个二维数组组成。
3. 深度优先搜索(DFS)
深度优先搜索即尽可能“深“的遍历一个图,在深度优先搜索中,对于最新已经发现的顶点,如果它的邻接顶点未被访问,则深度优先搜索该邻接顶点。
算法演示地址为:http://sjjg.js.zwu.edu.cn/SFXX/sf1/sdyxbl.html
伪代码如下:
完整c代码如下:
#include <stdio.h>
#define N 6
struct adj_matrix {
int vertex[N];
int edge[N][N];
};
struct adj_matrix matrix = {
{1, 2, 3, 4, 5, 6},
{{0, 1, 0, 1, 0, 0},
{0, 0, 0, 0, 1, 0},
{0, 0, 0, 0, 1, 1},
{0, 1, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 1}}
};
int visit[N] = {0, 0, 0, 0, 0, 0};
void dfs_visit(struct adj_matrix *G, int u)
{
int v;
visit[u] = 1;
printf("%3d", G->vertex[u]);
for (v = 0; v < N; v++) {
if (G->edge[u][v] == 1 && visit[v] != 1) {
dfs_visit(G, v);
}
}
}
void dfs(struct adj_matrix *G)
{
int u;
for (u = 0; u < N; u++) {
if (visit[u] != 1) {
dfs_visit(G, u);
}
}
}
int main(void)
{
dfs(&matrix);
printf("\n");
return 0;
}
遍历结果为:1 2 5 4 3 6