python recursive soltion


  • 0
    W

    '''class Solution(object):
    def exist(self, board, word):
    """
    :type board: List[List[str]]
    :type word: str
    :rtype: bool
    """

        if len(word) == 0:
            return True
        for i in range (len(board)):
            for j in range (len(board[0])):
                if board[i][j] == word[0]:
                    if len(word) == 1:
                        return True;
                 
                    if self.find(board,i,j,word,0):
                        return True
        return False
        
    def find(self, board,row,col, word,index):  
        board[row][col] = ' ';
        if index == len(word) - 1:
            return True
        else:
            
            if row + 1 < len(board) and board[row + 1][col] == word[index + 1]:        
                if self.find(board, row + 1, col, word, index + 1):
                    return True;
            if row - 1 >= 0 and board[row - 1][col] == word[index + 1]:       
                if self.find(board, row -1 ,col,word, index + 1):
                    return True
            if col + 1 < len(board[0])and board[row][col+1] == word[index + 1]:         
                if self.find(board, row, col + 1, word, index +1):
                    return True
            if col - 1 >= 0and board[row][col-1] == word[index + 1]:         
                if self.find(board, row, col -1, word, index + 1):
                    return True
            
        board[row][col] = word[index]
        return False
                
        '''

Log in to reply
 

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