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:
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.
解法
DFS. 遍历网格, 找到word[0]首字母的位置, 从这个位置起, 看能否找到一条路径能拼成word, 需要将已经访问过的位置进行标记.
代码
class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
# edge case
if not board: return False
r, c = len(board), len(board[0])
for i in range(r):
for j in range(c):
if board[i][j] == word[0] and self.dfs(board, word, i, j):
return True
return False
def dfs(self, board, word, i, j):
# all the letters are checked
if len(word) == 0:
return True
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[0]:
return False
temp = board[i][j]
# mark the visited cell
board[i][j] = '#'
res = self.dfs(board, word[1:], i-1, j) or self.dfs(board, word[1:], i+1, j) \
or self.dfs(board, word[1:], i, j-1) or self.dfs(board, word[1:], i, j+1)
board[i][j] = temp
return res
本文介绍了一种使用深度优先搜索(DFS)算法在二维网格中查找指定单词的方法。通过遍历网格,找到单词首字母的位置,并从该位置开始,检查是否能找到一条路径拼成整个单词,同时确保同一字母单元格不会被重复使用。
685

被折叠的 条评论
为什么被折叠?



