Depth-first search (DFS) algorithm

Table of contents

algorithm thinking

Time Complexity and Space Complexity

Algorithm implementation

Algorithm pros and cons

Application field


algorithm thinking

The idea of ​​the depth-first search (DFS) algorithm is to start from a certain starting vertex of the graph, follow a path to visit all the vertices in the graph as deeply as possible, until it cannot continue, and then return and explore other paths. Specifically, the DFS algorithm is implemented using a stack data structure. After visiting a vertex, its unvisited neighbors are pushed into the stack and marked as visited. Then take out the next unvisited vertex from the stack, and repeat the above process until the stack is empty.

Time Complexity and Space Complexity

The time complexity of the depth-first search (DFS) algorithm is O(V+E), where V is the number of vertices and E is the number of edges. This is because in the worst case all vertices and edges need to be visited to complete the traversal.

The DFS algorithm uses a stack data structure to store the vertices to be visited and their neighbor vertices, so the space complexity depends on the number of elements stored in the stack. In the worst case, that is, when the graph is a chain structure, the number of elements that the DFS algorithm needs to store reaches the O(V) level, so the space complexity is also O(V).

It should be noted that in practical applications, the space complexity of the DFS algorithm may be further reduced by the limitation of recursive calls. For some special cases, for example, the occupancy of storage space can be further reduced by means of pruning.

Algorithm implementation

The following is a basic C# depth-first search algorithm implementation:

 /// <summary>
    /// 深度优先搜索算法
    /// </summary>
    public class DepthFirstSearch
    {
        private int V; // 图形中的顶点数
        private List<int>[] adj; // 邻接表表示

        public DepthFirstSearch(int v)
        {
            V = v;
            adj = new List<int>[V];
            for (int i = 0; i < V; ++i)
                adj[i] = new List<int>();
        }

        public void AddEdge(int v, int w)
        {
            adj[v].Add(w); // 将 w 添加到 v 的邻接表中
        }

        // 深度优先遍历算法
        private void DFSUtil(int v, bool[] visited)
        {
            visited[v] = true;
            Console.Write(v + " ");

            foreach (int i in adj[v])
            {
                if (!visited[i])
                    DFSUtil(i, visited);
            }
        }

        // 从顶点 v 开始进行深度优先遍历
        public void DFS(int v)
        {
            bool[] visited = new bool[V];
            DFSUtil(v, visited);
        }

    }



static void Main(string[] args)
    {
        DepthFirstSearch g = new DepthFirstSearch(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);

        Console.WriteLine("从顶点 2 开始的深度优先遍历:");
        g.DFS(2);
    }

The implementation defines a DepthFirstSearchclass to represent a graph, which contains an array of adjacency lists and methods for adding edges and depth-first traversal. In DFSUtilthe method, a Boolean array is used visitedto keep track of visited vertices, and DFSUtilits unvisited neighbors are traversed by recursively calling . In DFSthe method, create a new visitedarray and call it starting from the specified starting vertex DFSUtil. Finally, Maincreate a new Graphinstance in the method and call DFSthe method to do a depth-first traversal starting from vertex 2. 

Algorithm pros and cons

Advantages of depth-first search algorithm:

  1. Easy to implement: C# depth-first search algorithm is relatively easy to implement, suitable for beginners to learn and understand.
  2. Low space complexity: When the depth of traversal exceeds the average depth of the graph, the space complexity of the C# depth-first search algorithm is lower than that of the breadth-first search algorithm.
  3. Find a path faster: Due to the nature of the depth-first search algorithm, it is easier to find a path from a start vertex to a goal vertex.

Disadvantages of depth-first search algorithm:

  1. Shortest path may not be found: Due to the nature of the depth-first search algorithm, it may not necessarily be able to find the shortest path from the start vertex to the goal vertex. When the target vertex is on a shallow level, it may need to traverse a large number of nodes to reach the vertex, resulting in low algorithm efficiency.
  2. Possibility to go into an infinite loop: If there are cycles in the graph, the depth-first search algorithm may get stuck in an infinite loop and fail to find a path from the starting vertex to any other vertex. Therefore, before applying the depth-first search algorithm, you must ensure that the input is free of cycles.
  3. Less efficient for graphs with forks: In graphs with a large number of branches, the depth-first search algorithm may remove many nodes, making the algorithm less efficient.

Application field

Depth-first search (DFS) algorithm is a basic graph traversal algorithm, which can be widely used in many fields. The following are some typical application areas:

  1. Graph traversal: The DFS algorithm can be used for graph traversal, including finding paths, connectivity, and loops.

  2. Search problems: By using backtracking techniques, the DFS algorithm can be used for search problems, such as maze problems, Sudoku problems, etc.

  3. Minimum spanning tree: By sorting all edges by weight and adding edges to the spanning tree in turn, the DFS algorithm can implement Prim's algorithm and Kruskal's algorithm to construct a minimum spanning tree.

  4. Directed Acyclic Graph: In Directed Acyclic Graph (DAG), the DFS algorithm can be used for problems such as topological sorting and calculating the longest path.

  5. Artificial intelligence: DFS algorithm can also be used in the field of artificial intelligence, such as Alpha-Beta pruning algorithm, heuristic search, etc.

In a word, DFS algorithm, as a basic graph traversal algorithm, has a wide range of applications and can solve various problems in many fields.

Guess you like

Origin blog.csdn.net/beenles/article/details/130729940