[Algorithm entry] Deep Priority Search (DFS)

Source: Internet
Author: User

Deep Priority Search (DFS)

[Algorithm entry]

Guo Zhiwei @ sysu: raphealguo (AT) QQ.com

1. Preface

Deep preference search (DFS) is similar to the breadth preference search. It is also an algorithm for traversing a connected graph. The idea is to start from a vertex V0 and go all the way to the end. If it finds that it cannot reach the target solution, it will return to the previous node and start from the other path to the end, the concept of depth-first is the concept of depth-first.

You can skip section 2 and read section 3 first,

2. Deep first search vs breadth first search 2.1 demonstrate the deep first search process

Let's refer to the example of the previous article. The starting point is still V0. Let's modify the meaning of the question, just let you find a path from V0 to V6, without the need for the shortest path.

Figure 2-1 find a path from V0 to V6 (no Shortest Path is required)

Assume that the search is in the following order:

1. V0-> V1-> V4. At the end of this time, V6 cannot be reached, so the original path is returned to V1 to search for other paths;

2. Search for V2 after returning to V1. The search path is V0-> V1-> v2-> V6. Find the target node and return a solution.

In this way, only two steps are available, but more steps are required if BFS is used.

2.2 comparison of depth and breadth

(You can skip this section to see section 3, with emphasis on section 3)

From the previous article titled [algorithm entry] breadth/width preference search (BFS), we found that a graph is searched by tree layers.

Assume that the average number of adjacent nodes derived from a node is N, so when the start point starts to search, there is a node in the queue. After the start point is obtained, put the adjacent nodes in the queue, so there are n nodes in the queue. When the elements are added to the queue in the current layer of search, the number of nodes reaches N2. You can think about it, once N is a relatively large number, the hierarchy of the tree is deep, so this queue needs a large memory space.

Therefore, the disadvantage of the breadth-first search is that memory consumption is very serious when the hierarchy of the tree is deep and the number of subnodes is large. Extended search is applicable to scenarios where the number of subnodes is small and the hierarchy of the tree is not too deep.

The depth first can overcome this shortcoming, because each layer requires only one node to be maintained during each search process. But let's look back and think about how to find the shortest path in breadth first. Can I find the depth first? The depth-first method is to go to the black line. Obviously, you cannot know if this path is the shortest path. So you have to continue to another path to determine whether it is the shortest path?

As a result, the disadvantages of deep Priority Search come out: it is difficult to find the optimal solution, but only to find a solution. The advantage is that the memory consumption is small, which overcomes the shortcomings of the extended search.

3. Deep Priority Search 3. 1. Example

The Figure 3-1 is shown. check whether a search path with a path length of 4 exists starting from V0 in the figure.


Figure 3-1

Obviously, we know that there is such a solution: V0-> V3-> V5-> V6.

. Handling process

3. pseudo-code corresponding to the example

Here we first provide the pseudo code for the above processing process.

/*** DFS core pseudocode **: the precondition is that all the visit arrays are set to false * @ Param N, the node currently being searched * @ Param D, that is, whether the path length * @ return has a solution */bool DFS (node N, int d) {If (D = 4) {// if the path length is true, return true;} For (node nextnode in N) {// traverses nodes adjacent to node n nextnode, if (! Visit [nextnode]) {// a node that has not been accessed can continue searching. // For example, If V1 is found, V1 must be set to visited visit [nextnode] = true; // The next step is to continue the access from V1. Of course, the path length must be added with if (DFS (nextnode, D + 1) {// if a solution is found, for example, V6, after finding the solution, you must recursively tell the upper layer that the solution has been found to return true;} // reset it to unaccessed, because it may appear in another path in the next search, visit [nextnode] = false;} // here, it is found that no solution has been found for this search, search from the next node of the current node .} Return false; // no solution for this search}

3.4.dfs function call stack

After that, the stack call will return to the layer v0, because no adjacent unaccessed node with v1.

After that, the stack call is returned to the layer V3.

After that, the stack call is returned to the place where the main function calls DFS (v0, 0). Because the solution has been found, no other paths need to be searched from other nodes.

4. Core code

The core code of DFS is provided first.

/*** DFS core pseudocode **: the precondition is that all the visit arrays are set to false * @ Param N, the node currently being searched * @ Param D, the depth currently reached * @ return, and whether there is a solution * /bool DFS (node N, int d) {If (isend (n, d) {// once the search depth reaches an end state, truereturn true is returned;} For (node nextnode in N) {// traverse n adjacent nodes nextnodeif (! Visit [nextnode]) {// visit [nextnode] = true; // In the next search, nextnode cannot appear if (DFS (nextnode, D + 1) again )) {// if a solution is found, // do other things, for example, return true for record result depth;} // reset it to false, because it may appear in another path in the next search, visit [nextnode] = false;} return false; // no solution for this search}

Of course, the visit array here is not necessarily necessary. In the 24-point example I will give, we can see this, here, visit only exists to ensure that the record node is not re-accessed. It can also be expressed in other ways. Here, only the core idea is given.

Deep-priority search algorithms require you to have a certain understanding of recursion. The important idea is: Abstraction!

We can see from the DFS function that only the current state node N is processed in the DFS, rather than the next state.

By abstracting the DFS method, the entire logic becomes very clear, which is the beauty of recursion.

5. Another example:. 1. Question description

I think everyone has played a game called "24: 00": Four integers are given. We need to use addition, subtraction, multiplication, division, and four operations to convert the calculation results to 24, and four numbers to be used in the calculation.

For example, four numbers are given: 1, 2, 3, and 4. I can use the following operation to obtain result 24:

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

As shown above, there are many combinations that make them 24, and of course there are also four numbers that cannot get results, such as 1, 1, 1, and 1.

Now I will give you four such numbers. Can you tell me they can be converted into 24 after a certain combination of operations? Here I give a constraint: decimals are not allowed in the division between numbers. For example, we can use 1/4 = 0.25, but the constraint here specifies that this operation is invalid.

5. Solution: Search Tree

For the sake of convenience, I suppose there are only three numbers, and only the addition and subtraction operations are allowed. I drew a search tree of 5-1.


Figure 5-1

There are only three numbers and only addition and subtraction, so there are at most six nodes on the second layer. If you are given four numbers and there is addition, subtraction, multiplication, and division, there will be more nodes on the second layer, when the number of nodes reaches the third layer, the disadvantages of using BFS are exposed, and a large space is required to maintain the queue. However, if you look at this search tree, the first layer is actually three numbers, and the second layer is actually two numbers, that is, the recursive depth will not exceed three layers, so it is more reasonable to use DFS to do this, the average efficiency is faster than BFS (I did not write code for verification, and the reader verifies it on his own ).

6. OJ questions

The question category comes from the network:

Sicily: 1019 1024 1034 1050 1052 1153 1171 1187

PKU: 1088 1176 1321 1416 1564 1753 2492 3083

7. Summary

DFS is suitable for such questions: given the initial status and target status, it is required to determine whether there is a solution from the initial status to the target status.

8. Expansion

I don't know if you have noticed that, in the process of deep/wide search, adding adjacent nodes has a certain policy, which has a great impact on the efficiency of the algorithm, you can have two simple questions, Ma Youxi and Ma Youxi. You will find that you are searching for them, using certain policies to access adjacent nodes can greatly improve the efficiency.

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

========================================================== ========================

This article is original. For more information, see raphealguo @ csdn.

Author: raphealguo (AT) QQ.com

Time:

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.