深度优先搜索

一 深度优先搜索

  个人感觉图的深度优先搜索算法二叉树的后序遍历算法有异曲同工之妙,均用递归实现。

    后序遍历算法首先访问该节点的子节点,然后访问本节点。

    深度优先搜索算法首先访问未被访问过的后续顶点,然后访问本顶点。

  深度优先搜索需要给节点着色,WHITE表示未被访问过的顶点,GRAY表示正在访问的顶点,BLACK表示已经访问过的顶点。

1 enum Color
2 {
3     WHITE,
4     GRAY,
5     BLACK
6 };

二 代码表示

  简单的图。

  1 首先需要定义顶点结构体Vertex

1 struct Vertex
2 {
3     int idx;
4     Color color;
5     Vertex *next;
6 
7     Vertex(int i=-1, Color c=WHITE, Vertex *n=NULL):idx(i), color(c), next(n) {  }
8 };

  2 定义相关操作,如初始化邻接表

 1 void addVertex(Vertex *pre, Vertex *next)
 2 {
 3     while (pre->next)
 4     {
 5         pre = pre->next;
 6     }
 7     pre->next = next;
 8 }
 9 
10 void init(Vertex *graph, int VertexNum)
11 {
12     for (int i=0;i<VertexNum;i++)
13     {
14         graph[i].idx = i;
15     }
16     // 0
17     addVertex(&graph[0], new Vertex(1));
18     addVertex(&graph[0], new Vertex(4));
19     //1
20     addVertex(&graph[1], new Vertex(0));
21     addVertex(&graph[1], new Vertex(2));
22     addVertex(&graph[1], new Vertex(3));
23     addVertex(&graph[1], new Vertex(4));
24     //2
25     addVertex(&graph[2], new Vertex(1));
26     addVertex(&graph[2], new Vertex(3));
27     //3
28     addVertex(&graph[3], new Vertex(1));
29     addVertex(&graph[3], new Vertex(2));
30     addVertex(&graph[3], new Vertex(4));
31     //4
32     addVertex(&graph[4], new Vertex(0));
33     addVertex(&graph[4], new Vertex(1));
34     addVertex(&graph[4], new Vertex(3));
35 }

  3 打印邻接表

 1 void printPath(Vertex * v)
 2 {
 3     while (v)
 4     {
 5         cout << "-->" << v->idx;
 6         v = v->next;
 7     }
 8 }
 9 
10 void printAdjacentList(Vertex *graph, int VertexNum)
11 {
12     cout << "打印邻接表:" << endl;
13     for (int i=0;i<VertexNum;i++)
14     {
15         cout << graph[i].idx;
16         printPath(graph[i].next);
17         cout << endl;
18     }
19 }

  4 深度优先搜索算法

 1 void DfsVisit(Vertex *graph, int idx)
 2 {
 3     graph[idx].color = GRAY; //正在访问的顶点着色GRAY
 4     Vertex *pre = &graph[idx];
 5     while (pre->next) // 访问所有后续顶点
 6     {
 7         if (graph[pre->next->idx].color == WHITE) // 访问所有未被访问过的后续顶点
 8             DfsVisit(graph, pre->next->idx);
 9         pre = pre->next;
10     }
11     graph[idx].color = BLACK; // 访问完成的顶点着色BLACK
12     cout << graph[idx].idx << endl;
13 }
14 
15 void DepthFirstSearch(Vertex *graph, int VertexNum)
16 {
17     cout << "深度遍历:" << endl;
18     for (int i=0;i<VertexNum;i++)
19         if (graph[i].color == WHITE)
20             DfsVisit(graph, i);
21 }

 

posted @ 2015-07-19 16:33  yoleimei  阅读(128)  评论(0编辑  收藏  举报