【问题标题】:Leetcode Word SearchLeetcode 单词搜索
【发布时间】:2021-07-26 10:31:27
【问题描述】:

我目前正在尝试解决Word Search problem on leetcode。问题如下:

给定一个 m x n 的字符板网格和一个字符串单词,如果网格中存在单词,则返回 true。

我的尝试如下:

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        def backtrack(loc: tuple, i: int) -> bool:
            x = loc[0]
            y = loc[1]
            if loc in seen:
                return False
            if  x >= len(board) or y >= len(board[0]):
                return False
            if 0 > x or 0 > y:
                return False
            if board[x][y] != word[i]:
                return False
            if i >= len(word)- 1:
                return True
            seen.add(loc)
            return backtrack((x+1, y), i+1) or backtrack((x-1, y), i+1) or backtrack((x, y-1), i+1) or backtrack((x,y+1), i+1)
        for i in range(len(board)):
            for j in range(len(board[i])):
                if board[i][j] == word[0]:
                    seen = set()
                    if backtrack((i, j), 0):
                        return True
        return False

现在我可以解决问题,如果我要编辑板输入以检查是否访问了状态,但我不想修改输入数组,所以我选择使用哈希集来完成。但是我无法正确实施检查,这就是我的代码失败的原因,所以我希望有人能帮助我。谢谢!

【问题讨论】:

    标签: algorithm data-structures backtracking


    【解决方案1】:

    对于回溯算法,您必须收回您所做的“移动”。所以在这种情况下,您必须在进行递归调用后从seen 中删除loc。这是一个建议的简单修复:

    class Solution:
        def exist(self, board: List[List[str]], word: str) -> bool:
            def backtrack(loc: tuple, i: int) -> bool:
                x = loc[0]
                y = loc[1]
                if loc in seen:
                    return False
                if  x >= len(board) or y >= len(board[0]):
                    return False
                if 0 > x or 0 > y:
                    return False
                if board[x][y] != word[i]:
                    return False
                if i >= len(word)- 1:
                    return True
                seen.add(loc)
                res = backtrack((x+1, y), i+1) or backtrack((x-1, y), i+1) or backtrack((x, y-1), i+1) or backtrack((x,y+1), i+1)
                seen.remove(loc)  # Removes loc from seen
                return res
            for i in range(len(board)):
                for j in range(len(board[i])):
                    if board[i][j] == word[0]:
                        seen = set()
                        if backtrack((i, j), 0):
                            return True
            return False
    

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2021-06-18
      • 2015-07-28
      • 2017-08-07
      • 2022-12-22
      • 1970-01-01
      相关资源
      最近更新 更多