# 深度优先搜索

• (a) 访问图中的一个节点；
• (b) 访问该节点的子节点；

DFS 算法可以通过不同方式来实现：

• 递归方式
• 非递归方式：使用栈（Stack）数据结构来存储遍历图中节点的中间状态；

DFS 算法的递归方式伪码如下：

1 procedure DFS(G,v):
2     label v as discovered
3     for all edges from v to w in G.adjacentEdges(v) do
4         if vertex w is not labeled as discovered then
5             recursively call DFS(G,w)

DFS 算法的非递归方式伪码如下：

1 procedure DFS-iterative(G,v):
2     let S be a stack
3     S.push(v)
4     while S is not empty
5           v ← S.pop()
6           if v is not labeled as discovered:
7               label v as discovered
8               for all edges from v to w in G.adjacentEdges(v) do
9                   S.push(w)

DFS 算法实现代码如下：

  1 using System;
2 using System.Linq;
3 using System.Collections.Generic;
4
5 namespace GraphAlgorithmTesting
6 {
7   class Program
8   {
9     static void Main(string[] args)
10     {
11       Graph g = new Graph(4);
18
19       foreach (var vertex in g.DFS(2))
20       {
21         Console.WriteLine(vertex);
22       }
23       foreach (var vertex in g.RecursiveDFS(2))
24       {
25         Console.WriteLine(vertex);
26       }
27
29     }
30
31     class Edge
32     {
33       public Edge(int begin, int end)
34       {
35         this.Begin = begin;
36         this.End = end;
37       }
38
39       public int Begin { get; private set; }
40       public int End { get; private set; }
41     }
42
43     class Graph
44     {
46         = new Dictionary<int, List<Edge>>();
47
48       public Graph(int vertexCount)
49       {
50         this.VertexCount = vertexCount;
51       }
52
53       public int VertexCount { get; private set; }
54
55       public void AddEdge(int begin, int end)
56       {
58         {
59           var edges = new List<Edge>();
61         }
62
64       }
65
66       public List<int> DFS(int start)
67       {
68         List<int> traversal = new List<int>();
69         int current = start;
70
71         // mark all the vertices as not visited
72         bool[] visited = new bool[VertexCount];
73         for (int i = 0; i < VertexCount; i++)
74         {
75           visited[i] = false;
76         }
77
78         // create a stack for DFS
79         Stack<int> stack = new Stack<int>();
80
81         // mark the current node as visited and push it
82         visited[current] = true;
83         stack.Push(current);
84
85         while (stack.Count > 0)
86         {
87           current = stack.Pop();
88
89           // if this is what we are looking for
91
92           // get all child vertices of the popped vertex,
93           // if a child has not been visited,
94           // then mark it visited and push it
96           {
97             foreach (var edge in _adjacentEdges[current].OrderByDescending(e => e.End))
98             {
99               if (!visited[edge.End])
100               {
101                 visited[edge.End] = true;
102                 stack.Push(edge.End);
103               }
104             }
105           }
106         }
107
108         return traversal;
109       }
110
111       public List<int> RecursiveDFS(int start)
112       {
113         List<int> traversal = new List<int>();
114         int current = start;
115
116         // mark all the vertices as not visited
117         bool[] visited = new bool[VertexCount];
118         for (int i = 0; i < VertexCount; i++)
119         {
120           visited[i] = false;
121         }
122
123         // traversal
124         RecursiveDFSTraversal(current, visited, traversal);
125
126         return traversal;
127       }
128
129       private void RecursiveDFSTraversal(int current, bool[] visited, List<int> traversal)
130       {
131         visited[current] = true;
133
135         {
136           foreach (var edge in _adjacentEdges[current].OrderBy(e => e.End))
137           {
138             if (!visited[edge.End])
139             {
140               RecursiveDFSTraversal(edge.End, visited, traversal);
141             }
142           }
143         }
144       }
145     }
146   }
147 }

## 参考资料

posted @ 2015-01-30 20:46  sangmado  阅读(3681)  评论(1编辑  收藏  举报