LeetCode-79 Word Search

Description

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 cells, where “adjacent” cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Constraints:
board and word consists only of lowercase and uppercase English letters.
• 1 <= board.length <= 200
• 1 <= board[i].length <= 200
• 1 <= word.length <= 10^3

Example

Example 1:
在这里插入图片描述Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
Output: true

Example 2:
在这里插入图片描述Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “SEE”
Output: true

Example 3:
在这里插入图片描述Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCB”
Output: false

Submissions

解题思路首先遍历数组,找到可能的起点 定义一个search函数,用来遍历当前起点的上下左右元素,看是否有符合给定单词的下一位的,如果有再递归调用search函数,当上下左右的下标越界或当前数组元素与当前的单词的字母不同时,返回False。

实现代码如下:

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

        def search(x:int, y:int, d:int) -> bool:
            if x>=m or x<0 or y>=n or y<0 or word[d] != board[x][y]: 
                return False
            if d == len(word)-1: 
                return True
            temp = board[x][y]
            board[x][y] = '0' # 标记遍历过的当前元素
            found = search(x,y-1,d+1) or search(x,y+1,d+1) or search(x-1,y,d+1) or search(x+1,y,d+1)   
            board[x][y] = temp # 还原标记过的元素
            return found

        for i in range(m):
            for j in range(n):
                if search(i, j, 0): return True
        return False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值