1, 算法用途:
用于遍历图中的节点, 有些类似于树的深度优先遍历. 这里唯一的问题是, 与树不同, 图形可能包含循环, 因此我们可能会再次来到同一节点.
2, 主要思想:
借用一个邻接表和布尔类型数组 (判断一个点是否查看过, 用于避免重复到达同一个点, 造成死循环等), 先将所有点按一定次序存入邻接表, 再通过迭代器, 对邻接表的 linklist 和布尔数组做出操作, 从而达到不重复递归遍历的效果.
(邻接表是表示了图中与每一个顶点相邻的边集的集合, 这里的集合指的是无序集)
3, 代码 (java):
- (以上图为例的代码)
- // 深度优先搜索
- import java.io.*;
- import java.util.*;
- //This class represents a directed graph using adjacency list
- //representation
- class Graph
- {
- private int V; // No. of vertices
- // Array of lists for Adjacency List Representation
- private LinkedList<Integer> adj[];
- // Constructor
- Graph(int v)
- {
- V = v;
- adj = new LinkedList[v];
- for (int i=0; i<v; ++i)
- adj[i] = new LinkedList();
- }
- //Function to add an edge into the graph
- void addEdge(int v, int w)
- {
- adj[v].add(w); // Add w to v's list.
- }
- // A function used by DFS
- void DFSUtil(int v,boolean visited[])
- {
- // Mark the current node as visited and print it
- visited[v] = true;
- System.out.print(v+" ");
- // Recur for all the vertices adjacent to this vertex
- Iterator<Integer> i = adj[v].listIterator();
- while (i.hasNext())
- {
- int n = i.next();
- if (!visited[n])
- DFSUtil(n,visited);
- }
- }
- // The function to do DFS traversal. It uses recursive DFSUtil()
- void DFS()
- {
- // Mark all the vertices as not visited(set as
- // false by default in java)
- boolean visited[] = new boolean[V];
- // Call the recursive helper function to print DFS traversal
- // starting from all vertices one by one
- for (int i=0; i<V; ++i)
- if (visited[i] == false)
- DFSUtil(i, visited);
- }
- public static void main(String args[])
- {
- Graph g = new Graph(4);
- g.addEdge(0, 1);
- g.addEdge(0, 2);
- g.addEdge(1, 2);
- g.addEdge(2, 0);
- g.addEdge(2, 3);
- g.addEdge(3, 3);
- System.out.println("Following is Depth First Traversal");
- g.DFS();
- }
- }
4, 复杂度分析:
DFS 复杂度分析 DFS 算法是一一个递归算法, 需要借助一个递归工作栈, 故它的空问复杂度为 O(V). 遍历图的过程实质上是对每个顶点查找其邻接点的过程, 其耗费的时间取决于所采用结构. 邻接表表示时, 查找所有顶点的邻接点所需时间为 O(E), 访问顶点的邻接点所花时间为 O(V), 此时, 总的时间复杂度为 O(V+E).
来源: https://www.cnblogs.com/Unicron/p/10849942.html