leetcood学习笔记-79-单词搜索

题目描述:

方法一;回溯

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        max_x,max_y,max_step = len(board)-1,len(board[0])-1,len(word)-1
        def maze(x, y,step,visited):
            if visited[x][y]==1:
                return False
            if board[x][y] != word[step]:
                return False
            if step==max_step:
                return True
            visited[x][y]=1
            if x < max_x and maze(x+1,y,step+1,visited):
                return True
            if x>0 and maze(x-1,y,step+1,visited):
                return True
            if y<max_y and maze(x,y+1,step+1,visited):
                return True
            if y>0 and maze(x,y-1,step+1,visited):
                return True
            # 记得失败后要置零
            visited[x][y]=0
            return False
        visited = [[0]*(max_y+1) for i in range(max_x+1)]
        for x in range(max_x+1):
            for y in range(max_y+1):
                if board[x][y] != word[0]:
                    continue
                if maze(x,y,0,visited):
                    return True
        return False

优化:

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        if not board: return False
        row = len(board)
        col = len(board[0])

        def dfs(word, i, j, visited):
            if not word:
                return True
            for li, lj in [[0,1],[1,0],[-1,0],[0,-1]]:
                tmp_i = i + li
                tmp_j = j + lj
                if 0 <= tmp_i < row and 0 <= tmp_j < col and word[0] == board[tmp_i][tmp_j] and (tmp_i,tmp_j) not in visited:
                    visited.add((tmp_i,tmp_j))
                    if dfs(word[1:], tmp_i,tmp_j, visited): return True
                    visited.remove((tmp_i,tmp_j))
            return False

        for i in range(row):
            for j in range(col):
                if board[i][j] == word[0] and dfs(word[1:], i, j,{(i,j)} ):
                    return True
        return False

 

 

posted @ 2019-04-22 19:33  oldby  阅读(154)  评论(0编辑  收藏  举报