问题:
给定一个2维字母组成的矩阵,水平或垂直的字母可以连成一个单词,给定一个单词,判断其是否在给定的矩阵中。每个字母只能被使用一次。
举例:
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
则根据规则:”ABCCED”, -> returns true,
“SEE”, -> returns true,
“ABCB”, -> returns false.
分析:
对于此问题,我们首先想到的方法是对于给定单词中的首字母在矩阵中进行遍历,寻找到开头的字母后,依次进行水平垂直移动,寻找第二个字母,直到遍历完单词中所有字母,若不存在即终止,说明没有查找到,否则说明单词存在于矩阵中。在实现我们的想法时,图结构最适合解决这个问题,我们可以利用DFS算法进行查找。具体代码如下:
def exist(self, board, word):
if not board:
return False
for i in xrange(len(board)):
for j in xrange(len(board[0])):
if self.dfs(board, i, j, word):
return True
return False
# check whether can find word, start at (i,j) position
def dfs(self, board, i, j, word):
if len(word) == 0: # all the characters are checked
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] # first character is found, check the remaining part
board[i][j] = "#" # avoid visit agian
# check whether can find "word" along one direction
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