1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Soultion: def helper(self, board, current, row, column): if len(current) == 0: return True
if 0 <= row < len(board) and 0 <= column < len(board[0]): if board[row][column] == current[0]: board[row][column] = "" if self.helper(board, current[1:], row - 1, column): return True if self.helper(board, current[1:], row + 1, column): return True if self.helper(board, current[1:], row, column - 1): return True if self.helper(board, current[1:], row, column + 1): return True board[row][column] = current[0] return False
def wordSearch(self, board, word): for i in range(len(board)): for j in range(len(board[0])): if self.helper(board, word, i, j): return True return False
if __name__ == '__main__': board = [['a', 'c', 'r', 'y', 'l'], ['l', 'w', 'o', 'r', 'i'], ['a', 'f', 'd', 'l', 'e'], ['k', 'e', 'e', 'w', 'e'], ['o', 'd', 'r', 'o', 's']] print(Soultion().wordSearch(board, "world"))
|