Slow by Easy Understanding Python


  • 0
    class Solution(object):
        def exist(self, board, word):
            if not board:
                return 0
            h, w = len(board), len(board[0])
            mark = [ [0 for i in xrange(w)] for j in xrange(h) ]
            def check(i, j, idx):
                if board[i][j] != word[idx]:
                    return False
                if idx == len(word) - 1:
                    return True
                dir = [[0, 1], [0, -1], [1, 0], [-1, 0]]
                for l in xrange(len(dir)):
                    ty, tx = i + dir[l][0], j + dir[l][1]
                    if 0<= ty < h and 0 <= tx < w and not mark[ty][tx]:
                        mark[ty][tx] = 1
                        if check(ty, tx, idx + 1):
                            return True
                        mark[ty][tx] = 0
                return False
            for i in xrange(h):
                for j in xrange(w):
                    if board[i][j] == word[0]:
                        mark = [ [0 for ww in xrange(w)] for hh in xrange(h) ]
                        mark[i][j] = 1
                        if check(i, j, 0):
                            return True
                        mark[i][j] = 0
            return False
    

Log in to reply
 

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