回溯法
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Word Search.
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.
'''
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
word_len = len(word)
if word_len == 0:
return True
row_len = len(board)
if row_len == 0:
return False
col_len = len(board[0])
if col_len == 0:
return False
if col_len * row_len < word_len:
return False
flag = [[False] * col_len for i in range(row_len)]
for row,s in enumerate(board):
for col,val in enumerate(s):
if val == word[0]:
flag[row][col] = True
if self._exist(board,row,col,row_len,col_len,word,1,word_len,flag) == True:
return True
flag[row][col] = False
return False
def _exist(self,board,row,col,row_len,col_len,word,index,word_len,flag):
'''最直观版本...也可以改成for循环,注意不要越界'''
if index >= word_len:
return True
if col > 0 and flag[row][col - 1] == False and board[row][col - 1] == word[index]:
flag[row][col - 1] = True
if self._exist(board,row,col - 1,row_len,col_len,word,index + 1 ,word_len,flag) == True:
return True
flag[row][col - 1] = False
if col < (col_len - 1) and flag[row][col + 1] == False and board[row][col + 1] == word[index]:
flag[row][col + 1] = True
if self._exist(board,row,col + 1,row_len,col_len,word,index + 1 ,word_len,flag) == True:
return True
flag[row][col + 1] = False
if row > 0 and flag[row - 1][col] == False and board[row - 1][col] == word[index]:
flag[row - 1][col] = True
if self._exist(board,row - 1,col,row_len,col_len,word,index + 1 ,word_len,flag) == True:
return True
flag[row - 1][col] = False
if row < (row_len - 1) and flag[row + 1][col] == False and board[row + 1][col] == word[index]:
flag[row + 1][col] = True
if self._exist(board,row + 1,col,row_len,col_len,word,index + 1 ,word_len,flag) == True:
return True
flag[row + 1][col] = False
return False
if __name__ == "__main__":
s = Solution()
a = [['A','B','C','E'],['S','F','C','S'],['A','D','E','E']]
print s.exist(a,'ABCCED')
print s.exist(a,'SEE')
print s.exist(a,'ABCB')