Depth-First search in Python

后端 未结 4 1522
南笙
南笙 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:29

    Well, first of all a depth-first search assumes a tree. Now, that makes sense here as you have several possible moves in most cases. A depth first-search would simply try the first possible move, and then the first possible move in the new situation, and the first possible move in that new situation, until success or no more possible moves, in which case it would back up until it finds a move it hasn't tried, and go down again.

    The "correct" way of doing that is with recursion. You have no recursion in your system as far as I can see.

    Something like this would work (pythonic psuedo codeish english):

    def try_next_move(self, board):
        for each of the pegs in the board:
            if the peg can be moved:
                new_board = board with the peg moved
                if new_board is solved:
                    return True
                if self.try_next_move(new_board):
                    return True
                # That move didn't lead to a solution. Try the next.
        # No move  worked.
        return False
    

提交回复
热议问题