Depth-First search in Python

后端 未结 4 1517
南笙
南笙 2021-02-06 13:37

I\'m trying to do a Depth-First search in Python but it\'s not working.

Basically we have a peg-solitaire board:

[1,1,1,1,1,0,1,1,1,1]

4条回答
  •  清歌不尽
    2021-02-06 14:21

    The normal way to implement DFS in a situation where each step is a "move" from a "board position" to some possible next one, until a goal is reached, is as follows (pseudocode)

    seenpositions = set()
    currentpositions = set([startingposition])
    while currentpositions:
      nextpositions = set()
      for p in currentpositions:
        seenpositions.add(p)
        succ = possiblesuccessors(p)
        for np in succ:
          if np in seenpositions: continue
          if isending(np): raise FoundSolution(np)
          nextpositions.add(np)
      currentpositions = nextpositions
    raise NoSolutionExists()
    

    You probably also want to keep backward links to be able to emit, at the end, the series of moves leading to the found solution (if any), but that's an ancillary problem.

    I don't recognize a trace of this general structure (or reasonable variant thereof) in your code. Why not try to record it this way? You only need to code possiblesuccessors and isending (if you insist on keeping a position as a list you'll have to turn it into a tuple to check membership in set and add to set, but, that's pretty minor;-).

提交回复
热议问题