单词搜索
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
代码解析: backtrack用来判定对于某个以word[0]开头的board中的一个字母,剩余的是否能形成word;主函数用来遍历所有字母
class Solution(object):
def __init__(self):
self.directions = [(0, 1), (-1, 0), (1, 0), (0, -1)]
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if not len(board):
return False
marked = [[0 for _ in range(len(board[0]))] for _ in range(len(board))]
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
marked[i][j] = 1
if self.backtrack(i, j, marked, board, word[1:]):
return True
else:
marked[i][j] = 0
return False
def backtrack(self, i, j, marked, board, word):
if len(word) == 0:
return True
for direction in self.directions:
cur_i = i + direction[0]
cur_j = j + direction[1]
if 0 <= cur_i < len(board) and 0 <= cur_j < len(board[0]) and board[cur_i][cur_j] == word[0]:
if marked[cur_i][cur_j]:
continue
else:
marked[cur_i][cur_j] = 1
if self.backtrack(cur_i, cur_j, marked, board, word[1:]):
return True
else:
marked[cur_i][cur_j] = 0
return False