LeetCode----Word Search

95 篇文章 0 订阅
93 篇文章 0 订阅

Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board = 

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word  =  "ABCCED" , -> returns  true ,
word  =  "SEE" , -> returns  true ,
word  =  "ABCB" , -> returns  false .


分析:

这题题目意思描述的不对。

当borad为[ ["ABCE"], ["SFCS"], ["ADEE"] ] 时,其应该为[ ["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"] ] 。

本题使用DFS来做。


代码:

class Solution(object):
    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        lines = len(board)
        rows = len(board[0])
        # 先判断board中的字符数是否足够word来访问
        if rows * lines < len(word):
            return False

        # 记录word中第一个字符在board中的位置,将从这些位置开始dfs遍历
        existposlst = []
        for i, l in enumerate(board):
            for j, r in enumerate(l):
                if r == word[0]:
                    existposlst.append([i, j])

        # 开始DFS
        for pos in existposlst:
            if self.dfs(board, rows, lines, word[1:], visistposlst=[pos], curpos=pos):
                return True
        return False

    def dfs(self, board, rows, lines, word, visistposlst, curpos):
        """
        :visistposlst: 列表类型,记录当前已经访问过的位置,不可重复访问(注意:集合类型无法hashable list)
        :curpos: 如[0, 1], 保存当前访问的位置
        :rtype: bool
        """
        if word == '':
            return True
        movedirect = [[-1, 0], [1, 0], [0, -1], [0, 1]]  # 上下左右
        for direct in movedirect:
            newpos = [curpos[0] + direct[0], curpos[1] + direct[1]]
            if 0 <= newpos[0] < lines and 0 <= newpos[1] < rows and board[newpos[0]][newpos[1]] == word[0]:
                if newpos not in visistposlst:
                    if self.dfs(board, rows, lines, word[1:], visistposlst + [newpos], newpos):
                        return True
        return False


后记:

本题我的代码效率并不高,但是却又找不到优化的办法。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值