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

学号:20011210126
姓名:刘岩哲
转载自:https://www.cnblogs.com/Unicron/p/10849942.html

【嵌牛导读】

深度优先搜索(缩写DFS)有点类似广度优先搜索,也是对一个连通图进行遍历的算法。它的思想是从一个顶点V0开始,沿着一条路一直走到底,如果发现不能到达目标解,那就返回到上一个节点,然后从另一条路开始走到底,这种尽量往深处走的概念即是深度优先的概念。

【嵌牛鼻子】深度优先搜索(DFS)思路及算法分析

【嵌牛正文】

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)。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。