Python----DFS---rider travel questions

Source: Internet
Author: User

This article will be a very classical and important concept in data structure and algorithm--depth first search (DEPTH-FIRST-SEARCH:DFS) ... (Did he not say it in the title?) )

Well, the essence of Dfs I have not yet made a special understanding, estimated to use more to understand the deeper.

!!! Knock the blackboard!!! The key to Dfs is recursion , recursion is really good!!!

Depth-First search (DFS)

What is DFS, faith can do hands on the principle of never noisy, directly to the online great God's blog link:

Well, actually this kind of link you can Baidu to. I will put here for reference, my main purpose is to talk about the knight travel problem.

Knight Travel Problem

What is the main content of the Knight travel problem? No nonsense, directly on the website:, this page is very clear about the DFS issue description. The author is the small turtle big God, I see in B station is his data structure course, occasionally opened a car almost flashed my waist.

Don't talk nonsense, don't you? (I was wrong, okay)

Well, directly on the code:

Importdatetime fromEnumImportEnumclassSize (Enum): X= () chess= [[0 forIinchRange (Size.x.value)] forJinchrange (size.x.value)]defnextxy (x, y, position):GlobalChessifPosition==0 andX-2>=0 andY-1>=0 andchess[x-2][y-1]==0:return[1, X-2, y-1]    elifPosition==1 andX-2>=0 andY+1<=size.x.value-1 andchess[x-2][y+1]==0:return[1, X-2, y+1]    elifposition==2 andX-1>=0 andY-2>=0 andchess[x-1][y-2]==0:return[1, X-1, y-2]    elifPosition==3 andX-1>=0 andY+2<=size.x.value-1 andchess[x-1][y+2]==0:return[1, X-1, y+2]    elifPosition==4 andX+1<=size.x.value-1 andY-2>=0 andchess[x+1][y-2]==0:return[1, X+1, y-2]    elifPosition==5 andX+1<=size.x.value-1 andY+2<=size.x.value-1 andchess[x+1][y+2]==0:return[1, X+1, y+2]    elifPosition==6 andX+2<=size.x.value-1 andY-1>=0 andchess[x+2][y-1]==0:return[1, X+2, y-1]    elifPosition==7 andX+2<=size.x.value-1 andY+1<=size.x.value-1 andchess[x+2][y+1]==0:return[1, X+2, y+1]    Else:        return[0, X, y]defTravelchessboard (x, y, tag):GlobalChess chess[x][y]=Tag    ifTag = = Size.x.value**2:         forIinchChess:Print(i)return "OK"F=0 forIinchRange (8): Flag=nextxy (x, y, i)ifflag[0]: Statues= Travelchessboard (flag[1], flag[2], tag+1)            ifstatues=="OK":                return "OK"F+ = 1Else: F+ = 1iff = = 8: Chess[x][y]=0Print(Travelchessboard (2, 0, 1))Print( ()-start)

The whole order code can be divided into three parts: the variable preparation part, the position judgment part, the cyclic recursive part .

1. Variable Preparation section:

      • Defines a size enumeration class, which is used to implement the function of the macro definition in the C language deliberately defined, of course, you can use other methods, mainly to facilitate the change of the size of the board.
      • Defines a checkerboard variable, which is a two-dimensional matrix with all elements initialized to 0. The chessboard in question.

2. Position Judgment section:

      • The function has three parameters, namely coordinates x, Y and position position, this position position first to explain, as shown in [1], in chess, according to the horse's Way (horse walking day) for any position, where the horse can go to a total of 8 locations, each position corresponding to the coordinate transformation is not the same , here the position corresponds to 8 kinds of coordinate transformation mode . (x, y) is the position coordinates of the horse at the current location
      • The returned parameter is a list of three elements , the first element indicates whether there is a next position in the 8 position that satisfies the condition, and if so, the second to third two returns the coordinates of the new position, and if not, returns the original coordinates
      • The criterion of judging is to satisfy two aspects at the same time: coordinates can not be out of bounds, coordinates corresponding position has not passed (the value of the position is 0), both are satisfied that there is the next position that satisfies the condition
    • Cyclic recursive functions:
1 defTravelchessboard (x, y, tag):2     GlobalChess3Chess[x][y] =Tag4     ifTag = = Size.x.value**2:5          forIinchChess:6             Print(i)7         return "OK"8f =09      forIinchRange (8):TenFlag =nextxy (x, y, i) One         ifFlag[0]: AStatues = Travelchessboard (flag[1], flag[2], tag+1) -             ifstatues=="OK": -                 return "OK" thef + = 1 -         Else: -f + = 1 -     iff = = 8: +Chess[x][y] = 0
    • The parameters passed in are the current position of the horse (x, y), and the number of steps (the tag value) that is currently walking.
    • Line 3 , chess[x][y] = tag, the value of the current position is equal to the current number of steps, the place is not reached is 0, in order to determine whether a position has been reached
    • Line 4-6 , if the number of steps is equal to the total number of squares (default is Teaboard), then print the chessboard, return to the "OK" state, tell the previous level of recursion has been found to the solution, no further search
    • Line 8 , define a process variable f = 0, the effect will be discussed later
    • Line 9-17 , to the horse's current position of the next 8 positions to traverse, for each position, if there is the next qualifying position to enter the recursion, the next position matching the condition as the current position in the recursive function, the number of steps plus 1. For 8-position traversal, the value of F is added one at a time where a non-qualifying position occurs.
    • Line 18-19 , when all 8 positions have been traversed, there is no qualifying position, then F = 8, indicating that the current position is not eligible, then reset the value of the current position to 0.
    • Again 12-15 , when the deep traversal cannot find a suitable position, the recursion is returned to the previous level, indicating that the current position of the previous layer does not match the condition, then the value of f must be 1, then continue to traverse the next position in the previous layer, and so on.
    • Finally, 13-14 Line, when the path has been found and printed out, the program after the "OK" status, the program's recursion from the last layer continues to return, in order to speed up the end of the program, do not continue to carry out the rest of the traversal, each layer of recursion will be directly returned. If you do not return directly, the program will go through all the conditions and then return, so that the time will be very very very long. You CAN have A TRY!!!

This program is almost finished, I think as long as the understanding of recursion, the program should not be difficult to understand.

For a few days in a row with recursion, the use of recursion is becoming more and more skilled, indeed very useful, and sincerely hope that this article will help you.

May you have a successful study!!!

[1] Figure copy from, thanks to Fish C Studio.

Python----DFS---rider travel questions

Related Article

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: 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.