题目描述:
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.
For example,
Given board =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.
我的思路:
给出了一个二维矩阵,确定一个单词是否在其中,要求的条件是只能使用相邻的字母。就是能不能在矩阵找出一个路径正好是给出的单词。还是DFS,每个矩阵元素循环一次,进行一次DFS,每次进行一次判断。超出边界还有board[i][j] != word[0],就返回False,最后word全部检查完毕就返回True。
我的代码:
class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if not board:
return False
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(board, i, j, word):
return True
return False
def dfs(self, board, i, j, word):
if len(word) == 0:
return True
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or word[0] != board[i][j]:
return False
tmp = board[i][j]
board[i][j] = '&'
res = self.dfs(board, i+1, j, word[1:]) or self.dfs(board, i-1, j, word[1:]) or self.dfs(board, i, j+1, word[1:]) or self.dfs(board, i, j-1, word[1:])
board[i][j] = tmp
return res
Discuss:
学到:
深度优先搜索是解决这种查找问题的好方法。使用是注意递归的出口,和路径。