【Leetcode】剑指Offer 12:矩阵中的路径

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
例如,在下面的 3×4 的矩阵中包含单词 “ABCCED”(单词中的字母已标出)。
示例 1:
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
输出:true
示例 2:
输入:board = [[“a”,“b”],[“c”,“d”]], word = “abcd”
输出:false
提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board 和 word 仅由大小写英文字母组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/ju-zhen-zhong-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

第一版WA代码

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        def judgeLeagel(a:tuple, m:int, n:int) -> bool:
            return a[0] >= 0 and a[0] < m and a[1] >= 0 and a[1] < n

        

        def getpath(path: List[tuple], word:str, m:int, n:int) -> bool:
            currentx, currenty = path[-1]
            alist = []
            alist.append((currentx, currenty + 1))
            alist.append((currentx, currenty - 1))
            alist.append((currentx + 1, currenty))
            alist.append((currentx - 1, currenty))
            b = [False, False, False, False]

            for i, a in enumerate(alist):
                if judgeLeagel(a, m, n) and board[a[0]][a[1]] == word[0] and a not in path:
                    if len(word) == 1:
                        return True
                    else:
                        # temp = copy.deepcopy(path)
                        # temp.append(a)
                        temp = path
                        temp.append(a)
                        b[i] = getpath(temp, word[1:], m, n)
                        if b[i] == True:
                            return True
            else:
                return False
        if len(word) == 1:
            for l in board:
                if word in l:
                    return True
            else:
                return False

        alphalist = []
        for i, a in enumerate(board):
            for j, n in enumerate(a):
                if n == word[0]:
                    alphalist.append((i, j))
        if alphalist == []:
            return False
        else:
            for a in alphalist:
                if getpath([a], word[1:], len(board), len(board[0])):
                    return True
            else:
                return False



错误原因本质是由Python的深浅拷贝机制导致的,直接赋值的方式使得temp和path本质是一个引用,因此在递归返回时path的元素并不会消失

第二版WA代码

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        def judgeLeagel(a:tuple, m:int, n:int) -> bool:
            return a[0] >= 0 and a[0] < m and a[1] >= 0 and a[1] < n

        

        def getpath(path: List[tuple], word:str, m:int, n:int) -> bool:
            currentx, currenty = path[-1]
            alist = []
            alist.append((currentx, currenty + 1))
            alist.append((currentx, currenty - 1))
            alist.append((currentx + 1, currenty))
            alist.append((currentx - 1, currenty))
            b = [False, False, False, False]

            for i, a in enumerate(alist):
                if judgeLeagel(a, m, n) and board[a[0]][a[1]] == word[0] and a not in path:
                    if len(word) == 1:
                        return True
                    else:
                        temp = copy.deepcopy(path)
                        temp.append(a)
                        b[i] = getpath(temp, word[1:], m, n)
                        if b[i] == True:
                            return True
            else:
                return False
        if len(word) == 1:
            for l in board:
                if word in l:
                    return True
            else:
                return False

        alphalist = []
        for i, a in enumerate(board):
            for j, n in enumerate(a):
                if n == word[0]:
                    alphalist.append((i, j))
        if alphalist == []:
            return False
        else:
            for a in alphalist:
                if getpath([a], word[1:], len(board), len(board[0])):
                    return True
            else:
                return False



WA的原因是超时,这是由于深拷贝对内存和计算量都有很大的负担。

AC代码

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        def judgeLeagel(a:tuple, m:int, n:int) -> bool:
            return a[0] >= 0 and a[0] < m and a[1] >= 0 and a[1] < n

        

        def getpath(path: List[tuple], word:str, m:int, n:int) -> bool:
            currentx, currenty = path[-1]
            alist = []
            alist.append((currentx, currenty + 1))
            alist.append((currentx, currenty - 1))
            alist.append((currentx + 1, currenty))
            alist.append((currentx - 1, currenty))
            b = [False, False, False, False]

            for i, a in enumerate(alist):
                if judgeLeagel(a, m, n) and board[a[0]][a[1]] == word[0] and a not in path:
                    if len(word) == 1:
                        return True
                    else:
                        # temp = copy.deepcopy(path)
                        # temp.append(a)
                        path.append(a)
                        b[i] = getpath(path, word[1:], m, n)
                        path.remove(a)
                        if b[i] == True:
                            return True
            else:
                return False
        if len(word) == 1:
            for l in board:
                if word in l:
                    return True
            else:
                return False

        alphalist = []
        for i, a in enumerate(board):
            for j, n in enumerate(a):
                if n == word[0]:
                    alphalist.append((i, j))
        if alphalist == []:
            return False
        else:
            for a in alphalist:
                if getpath([a], word[1:], len(board), len(board[0])):
                    return True
            else:
                return False



利用remove的方法就能够实现上面的需求,笔者由于最开始只想着引用和深浅拷贝的问题,忽略了直接通过remove一样可以达到这样的效果。许久不做DFS的题目对一些简单的技巧都忘光了。好在写题的时候已经意识到了一部分剪枝的问题,最后勉强AC。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值