题目
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
提示:
- board 和 word 中只包含大写和小写英文字母。
- 1 <= board.length <= 200
- 1 <= board[i].length <= 200
- 1 <= word.length <= 10^3
解答
# encoding: utf-8
# 典型的深搜题目
# Time: O(m·n), Space: O(m·n)
class Solution:
def exist(self, board, word):
def dfs(x, y, s_index):
if s_index == len(word): # 匹配完成了
return True
for i in range(4):
tx = x + next[i][0]
ty = y + next[i][1]
if 0 <= tx < rows and 0 <= ty < columns and board[tx][ty] == word[s_index]:
temp = board[tx][ty]
board[tx][ty] = '/'
if dfs(tx, ty, s_index + 1):
return True
board[tx][ty] = temp
return False
if not board:
return False
next = [ # 右下左上
[0, 1],
[1, 0],
[0, -1],
[-1, 0]
]
columns, rows = len(board[0]), len(board)
# book = [[0 for _ in range(columns)] for _ in range(rows)] # 标记
s_index = 0
for i in range(rows):
for j in range(columns):
if board[i][j] == word[s_index]:
temp = board[i][j] # 不用book标记了,存入临时变量并修改board[i][j]为特殊字符,和原来自己的book标记思路相比,节省了O(mn)的空间
board[i][j] = '/'
if dfs(i, j, s_index + 1):
return True
board[i][j] = temp
return False
s = Solution()
ans = s.exist([["a", "b", "c", "e"],
["s", "f", "c", "s"],
["a", "d", "e", "e"]], 'bfce')
print(ans) # True