首页 > 其他 > 详细

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

时间:2019-04-22 20:28:18      阅读:131      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

方法一;回溯

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:
        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)]
        need={}
        for c in word:
            if c in need:
                need[c]+=1  
            else:
                need[c]=1
        for i in range(max_x+1):
            for j in range(max_y+1):
                if board[i][j] in need:
                    need[board[i][j]] -=1
        for c in need:
            if need[c] >0:
                return False
        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

 

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

原文:https://www.cnblogs.com/oldby/p/10752430.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!