Leetcode 79.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.

Example:

1
2
3
4
5
6
7
8
9
10
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

解题思路

回朔法,从board中每个元素出发遍历周围的四个元素,查看是否能组成部分答案,若能,则继续从该元素出发进行查找。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def find(board, x, y, word, i):
if i == len(word):
return True
if x < 0 or y < 0 or x == len(board) or y == len(board[0]) or board[x][y] != word[i]:
return False
tmp = board[x][y]
board[x][y] = "#"
exists = find(board, x+1, y, word, i+1) \
or find(board, x, y+1, word, i+1) \
or find(board, x-1, y, word, i+1) \
or find(board, x, y-1, word, i+1)
board[x][y] = tmp
return exists
if not board:
return False
h = len(board)
w = len(board[0])
for i in range(len(board)):
for j in range(len(board[0])):
if find(board, i, j, word, 0):
return True
return False