79. Word Search

79. Word Search

Medium

5500242Add to ListShare

Given an m x n grid of characters board and a string word, return true if 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.

 

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

 

Constraints:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters.

 

Follow up: Could you use search pruning to make your solution faster with a larger board?

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        """
        解题思路:广度优先,枚举矩阵的字符,上下左右广度优先查找,找到则返回true,否则最后返回false
        :param board: 字符矩阵
        :param word: 要找的单词
        :return: 是否存在
        """
        # 上下左右
        directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
        n = len(board)
        m = len(board[0])

        def bfs(x: int, y: int, match_num: int) -> bool:
            """
            广度优先
            :param x: 当前x坐标
            :param y: 当前y坐标
            :param match_num: 已匹配数
            :return: 是否找到
            """
            if board[x][y] != word[match_num]:
                return False
            match_num += 1
            if match_num >= len(word):
                return True
            for k in range(len(directions)):
                x1 = x + directions[k][0]
                if x1 < 0 or x1 >= n:
                    continue
                y1 = y + directions[k][1]
                if y1 < 0 or y1 >= m:
                    continue
                if board[x1][y1] == ".":
                    continue

                tmp = board[x][y]
                board[x][y] = "."
                result = bfs(x1, y1, match_num)
                board[x][y] = tmp
                if result:
                    return True
            return False

        for i in range(n):
            for j in range(m):
                if bfs(i, j, 0):
                    return True
        return False

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值