Accepted Python 11 lines DFS solution

  • 0
    def exist(board, word):
        R, C = len(board), len(board[0])
        def sink(r,c, w):
            if not w: return True
            if 0 <= r < R and 0<= c < C and board[r][c] == w[0]:
                board[r][c] = board[r][c]+'_' # append '_' to visited elements on board
                result = map(sink, [r, r, r+1, r-1], [c+1, c-1, c, c], [w[1:]]*4)
                if True in result: return True
                else: board[r][c] = board[r][c][0] # backtrack trailing '_' if w[1:] not found in children
            return False
        res = [sink(r,c,word) for r in range(R) for c in range(C) if board[r][c] == word[0]]
        return True in res

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.