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
andword
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