Depth-First search (DFS) detailed

Source: Internet
Author: User

Depth-First search (DFS)

"Getting Started with algorithms"


1. Preface

Depth-First search (abbreviated DFS) is a bit like breadth-first search and an algorithm for traversing a connected graph. Its idea is to start at a vertex of V0 , along a road to the end, if found not to reach the target solution, then return to the previous node, and then from the other road to go to the end, This concept of being as deep as possible is the concept of depth first.

You can skip the second section and look at section three first,:)

2. Depth-First searchVSBreadth First Search
2.1 Demonstrating the process of depth-first search

or refer to the sample diagram of the previous article, the starting point is still V0, we modify the meaning of the topic, just let you find a v0 to v6 Road, without the shortest path.

Figure 2-1 finding a path from v0 to v6 (no shortest path required)

Suppose to search in the following order:

1.v0->v1->v4, at this point in the end, still can't reach V6, so the original road back to V1 to search other paths;

2. Return to V1 after both search V2, so the search path is v0->v1->v2->v6,find the target node, return a solution.

The search is only 2 steps away, but it takes a few more steps if you use BFS .

2.2 Comparison of depth and breadth

(You can skip this section first look at section three, focusing on section III)

From the previous article, "Getting Started with the algorithm" breadth / Breadth First search (BFS) , we know that we search for a graph based on the tree hierarchy.

We assume that the average number of adjacent nodes derived from a node is n , then when the start of the search, the queue has a node, when the starting point is taken out, put its adjacent nodes in, then the queue has n nodes, In the next layer of the search to add elements to the queue, the number of nodes reached N2, you can think, once N is a relatively large number, the level of the tree is relatively deep, then this queue needs a lot of memory space.

So the breadth of the first search disadvantage came out: in the tree layer of deep & sub-nodes more than the case, the consumption of memory is very serious. Breadth-first search applies to nodes where the number of child nodes is not much, and the tree hierarchy is not too deep.

So depth first can overcome this disadvantage, because each search process, each layer only need to maintain one node. But back to think, breadth first can find the shortest path, that depth first can find it? Depth first method is a road to the black, it is clear that the road is not the shortest, so you still have to go another way to determine whether the shortest way?

So the downside of depth-first search comes out: it is difficult to find the best solution, only to find the solution. The advantage is that memory consumption is small, overcoming the shortcomings of the breadth-first search that has just been said.

3. Depth-First search
3.1. For example

Given the figure shown in 3-1 , figure out the V0 , whether there is a path length of 4 search path.


Figure 3-1

Obviously, we know there is a solution to this: V0->v3->v5->v6.

3.2. Process

3.3. Pseudo-code for the corresponding example

This first gives the corresponding pseudo-code of the upper processing.

/**  * DFS Core pseudocode * Precondition is that the  visit array is all set to False  * @param n the node currently starting the search  * @param d The depth currently reached, that is, the path length  * @return Whether there is a solution  *  /bool DFS (Node n, int d) {      if (d = = 4) {//path length is returned true, indicating that this search has a solution of          return true;      }        For (node NextNode in n) {//traversal nodes adjacent to Node n nextnode,          if (!visit[nextnode]) {///not visited nodes to continue searching                //For example, to search for V1, So V1 to be set to visited              visit[nextnode] = true;                The next step is to continue the visit from V1, the path length of course to add if                (DFS (NextNode, d+1)) {//If the search out has a solution                  //For example to the V6, to find the solution, you have to tell the upper layer of a recursive level has found the solution                  return true;              }                Reset to not access, because it may appear in the next search in the other path              visit[nextnode] = false;            }          Here, we find that the search has not yet found the solution, it is necessary to start the search from the next node of the current node.      }      Return false;//This search no solution  }  

Call stacks for 3.4.DFS functions

The stack call is then returned to the V0 layer, because the V1 layer cannot find adjacent nodes with V1

The stack call is then returned to the V3 layer

The stack call then returns to the location where the main function called DFS (v0,0), because the solution has been found and no more paths have to be searched from other nodes.

4. Core code

The core code for DFS is given here first.

/**  * DFS core pseudocode  * Precondition is that the visit array is all set to False  * @param n the node currently being searched  * @param d The depth currently reached  * @return If there is a solution  * /  bool DFS (Node n, int d) {      if (Isend (n, D)) {//Once the search depth reaches an end state, it returns true return True          ;      }        For (node NextNode in n) {//traversal n adjacent Nodes NextNode          if (!visit[nextnode]) {//              Visit[nextnode] = true;//in the next search, NextNode cannot reappear if              (DFS (NextNode, d+1)) {//If the search has a solution                  //To do something else, such as record the depth of the result, etc.                  return true;              }                Reset to False because it may appear in the next search in the other path              visit[nextnode] = false;}      }      Return false;//This search no solution  }  


Of course, the visit array here is not necessarily necessary, and in a few of the examples I gave in a few points, we can see this, where the visit exists just to ensure that the record node is not re-accessed, There are other ways to express it, and here are just the core ideas.

Depth-First search algorithm requires you to have a certain understanding of recursion, the important idea is: abstract!

You can see from the DFS function that theDFS inside always handles only the current state node n, not the next state.

by abstracting the DFS method, the whole logic becomes very clear, which is the beauty of recursion.

5. Another example: -Point 5.1. Title Description

Presumably everyone has played a game, called "The point": Give 4 integers, requires the subtraction 4 operations to make its operation results into a,4 of the number is not repeated use in the calculation.

For example, 4 numbers are given:1,2,3,4. I can get results with the following arithmetic:

1*2*3*4 =2*3*4/1 =(1+2+3) *4=24;..

As above, there are a lot of combinations to make them into a, of course, there is no result of the 4 number, such as:1,1,1,1.

Now I'm going to give you 4 of these, can you tell me if they can be converted into a number after a certain combination of operations? Here I give the constraint that no decimal is allowed in the division between numbers, for example, we can 1/4=0.25, but the constraints here specify that the operation is illegal.

5.2. Solution: Search Tree

To facilitate the narrative, I assume that there are now only 3 numbers, which allow addition and subtraction operations only. I have drawn a search tree for 5-1 .


Figure 5-1

There are only 3 of the number and only add and subtract, so the second layer of the node up to 6 , if it is to give you 4 number and subtraction, then the second layer of nodes will be more, when extended to the third layer when the number of nodes is more, using The shortcomings of BFS are exposed and require a lot of space to maintain that queue. And you see this search tree, in fact, the first layer is 3 number, to the second layer becomes 2 number, that is, recursion depth will not exceed 3 layers, so the use of DFS to do more reasonable, average efficiency than BFS Fast (I did not write code verification, the reader self-authentication).

6.OJ topics

Topic Classification from the network:

Sicily:1019 1034 1050 1052 1153 1171 1187

PKU:1088 1176 1321 1416 1564 1753 2492 3083 3411

7. Summary

DFS is suitable for this type of topic: Given the initial state and the target State, it is required to determine whether there is a solution from the initial state to the target State.

8. Expansion

I don't know if you noticed. In the depth / breadth of the search process, in fact, the addition of adjacent nodes if there is a certain strategy, the efficiency of the algorithm has a great impact, you can do a simple horse travel with the horse around The two questions, you have some experience, You will find that in the process of searching, using a certain strategy to access the neighboring nodes will increase the efficiency greatly.

With these greedy ideas, you can look at heuristic search algorithms, such as a * algorithm.


Depth-First search (DFS) detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.