深度优先搜索(DFS)思路及算法分析


1、算法用途

用于遍历图中的节点,有些类似于树的深度优先遍历。这里唯一的问题是,与树不同,图形可能包含循环,因此我们可能会再次来到同一节点。

 

2、主要思想

借用一个邻接表和布尔类型数组(判断一个点是否查看过,用于避免重复到达同一个点,造成死循环等),先将所有点按一定次序存入邻接表,再通过迭代器,对邻接表的linklist和布尔数组做出操作,从而达到不重复递归遍历的效果。

(邻接表是表示了图中与每一个顶点相邻的边集的集合,这里的集合指的是无序集)

 

3、代码(java)

(以上图为例的代码)

 1 //深度优先搜索
 2 import java.io.*;  3 import java.util.*;  4 
 5 //This class represents a directed graph using adjacency list  6 //representation 
 7 class Graph  8 {  9     private int V; // No. of vertices 10 
11     // Array of lists for Adjacency List Representation 
12     private LinkedList<Integer> adj[]; 13 
14     // Constructor 
15     Graph(int v) 16  { 17         V = v; 18         adj = new LinkedList[v]; 19         for (int i=0; i<v; ++i) 20             adj[i] = new LinkedList(); 21  } 22 
23     //Function to add an edge into the graph 
24     void addEdge(int v, int w) 25  { 26         adj[v].add(w); // Add w to v's list. 
27  } 28 
29     // A function used by DFS 
30     void DFSUtil(int v,boolean visited[]) 31  { 32         // Mark the current node as visited and print it 
33         visited[v] = true; 34         System.out.print(v+" "); 35 
36         // Recur for all the vertices adjacent to this vertex 
37         Iterator<Integer> i = adj[v].listIterator(); 38         while (i.hasNext()) 39  { 40             int n = i.next(); 41             if (!visited[n]) 42  DFSUtil(n,visited); 43  } 44  } 45 
46     // The function to do DFS traversal. It uses recursive DFSUtil() 
47     void DFS() 48  { 49         // Mark all the vertices as not visited(set as 50         // false by default in java) 
51         boolean visited[] = new boolean[V]; 52 
53         // Call the recursive helper function to print DFS traversal 54         // starting from all vertices one by one 
55         for (int i=0; i<V; ++i) 56             if (visited[i] == false) 57  DFSUtil(i, visited); 58  } 59 
60     public static void main(String args[]) 61  { 62         Graph g = new Graph(4); 63      
64         g.addEdge(0, 1); 65         g.addEdge(0, 2); 66         g.addEdge(1, 2); 67         g.addEdge(2, 0); 68         g.addEdge(2, 3); 69         g.addEdge(3, 3); 70 
71         System.out.println("Following is Depth First Traversal"); 72 
73  g.DFS(); 74  } 75 } 

 

4、复杂度分析

DFS复杂度分析 DFS算法是一一个递归算法,需要借助一个递归工作栈,故它的空问复杂度为O(V)。 遍历图的过程实质上是对每个顶点查找其邻接点的过程,其耗费的时间取决于所采用结构。 邻接表表示时,查找所有顶点的邻接点所需时间为O(E),访问顶点的邻接点所花时间为O(V),此时,总的时间复杂度为O(V+E)。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM