leetcode 79: 单词搜索

题目描述:
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
1.在这里插入图片描述
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
输出:true
2.在这里插入图片描述

输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “SEE”
输出:true
3.在这里插入图片描述
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCB”
输出:false
思路:
利用回溯的方式,对整个board进行搜索,但是在搜索的时候有几个需要注意的地方:
1)开始的字母在board可能有好几个位置。
2)在查找是否有这个词的时候,需要保证board中的字母只能使用一次。

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        if len(board) == 0 or len(board[0]) == 0:
            return False
        flag = False
        self.result = []
        i = []
        j = []
        for x in range(len(board)):
            for y in range(len(board[0])):
                if board[x][y] == word[0]:
                    flag = True
                    i.append(x)
                    j.append(y)

        if flag:
            count = 1
            s = set()
            for c in range(len(i)):
                # print("初始位置在:", i[c], j[c])
                s.add((i[c], j[c]))
                self.exist_sub(i[c], j[c], board, word, count, s)
                s.remove((i[c], j[c]))
            # print("返回的结果:", self.result)
            for r in range(len(self.result)):
                if self.result[r]:
                    return True
            return False
        else:
            return False

    def exist_sub(self, i, j, board, word, count, s):
        # 从上下左右四个方向进行搜索
        # print(count)
        # print(self.result)
        if count == len(word):
            self.result.append(True)
            # print(self.result)
            return
        if i >= 1 and board[i-1][j] == word[count]:
            if (i-1, j) not in s:
                s.add((i-1, j))
                self.exist_sub(i-1, j, board, word, count+1, s)
                s.remove((i-1, j))
        if i+1 < len(board) and board[i+1][j] == word[count]:
            if (i + 1, j) not in s:
                s.add((i + 1, j))
                self.exist_sub(i+1, j, board, word, count+1, s)
                s.remove((i + 1, j))
        if j >= 1 and board[i][j-1] == word[count]:
            if (i, j - 1) not in s:
                s.add((i, j - 1))
                self.exist_sub(i, j-1, board, word, count+1, s)
                s.remove((i, j - 1))
        if j+1 < len(board[0]) and board[i][j+1] == word[count]:
            if (i, j + 1) not in s:
                s.add((i, j+1))
                self.exist_sub(i, j+1, board, word, count+1, s)
                s.remove((i, j+1))
        # print("都没找到")
        self.result.append(False)

思路2:
设函数 check(i,j,k) 表示判断以网格的 (i,j) 位置出发,能否搜索到单词 word[k…],其中 word[k…] 表示字符串 word 从第 kk 个字符开始的后缀子串。如果能搜索到,则返回 true,反之返回false。函数check(i,j,k) 的执行步骤如下:

如果board[i][j] !=s[k],当前字符不匹配,直接返回false。
如果当前已经访问到字符串的末尾,且对应字符依然匹配,此时直接返回true。
否则,遍历当前位置的所有相邻位置。如果从某个相邻位置出发,能够搜索到子串 word[k+1…],则返回 }true,否则返回false。
这样,我们对每一个位置 (i,j) 都调用函数 check(i,j,0) 进行检查:只要有一处返回 }true,就说明网格中能够找到相应的单词,否则说明不能找到。

为了防止重复遍历相同的位置,需要额外维护一个与 board 等大的 visited 数组,用于标识每个位置是否被访问过。每次遍历相邻位置时,需要跳过已经被访问的位置。

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

        def check(i: int, j: int, k: int) -> bool:
            if board[i][j] != word[k]:
                return False
            if k == len(word) - 1:
                return True
            
            visited.add((i, j))
            result = False
            for di, dj in directions:
                newi, newj = i + di, j + dj
                if 0 <= newi < len(board) and 0 <= newj < len(board[0]):
                    if (newi, newj) not in visited:
                        if check(newi, newj, k + 1):
                            result = True
                            break
            
            visited.remove((i, j))
            return result

        h, w = len(board), len(board[0])
        visited = set()
        for i in range(h):
            for j in range(w):
                if check(i, j, 0):
                    return True
        
        return False

复杂度:
时间复杂度:一个非常宽松的上界为O(MN⋅3 ^L
),其中 M, NM,N 为网格的长度与宽度,L 为字符串word 的长度。在每次调用函数 check 时,除了第一次可以进入 44 个分支以外,其余时间我们最多会进入 3 个分支(因为每个位置只能使用一次,所以走过来的分支没法走回去)。由于单词长为 L,故check(i,j,0) 的时间复杂度为 O(3^L),
而我们要执行 O(MN) 次检查。然而,由于剪枝的存在,我们在遇到不匹配或已访问的字符时会提前退出,终止递归流程。因此,实际的时间复杂度会远远小于 Θ(MN⋅3 ^L)。

空间复杂度:O(MN)。我们额外开辟了 O(MN) 的visited 数组,同时栈的深度最大为 O(min(L,MN))。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值