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