递归和回溯_leetcode79

class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""


self.d = [[-1,0],[0,1],[1,0],[0,-1]]
self.m = len(board)
self.n = len(board[0])
self.visit =[[False for i in range(self.n)] for j in range(self.m)]

for x in range(0,self.m):
for y in range(0,self.n):
if self.searchWord(board,word,0,x,y):
return True

return False

def inArea(self,x,y):
return x >= 0 and x < self.m and y >= 0 and y < self.n

def searchWord(self,board,word,index,startX,startY):

if index == len(word)-1:
return board[startX][startY] == word[index]




if board[startX][startY] == word[index]:

self.visit[startX][startY] = True

for item in self.d:
newX = startX + item[0]
newY = startY + item[1]

if self.inArea(newX,newY) and self.visit[newX][newY] == False:
if self.searchWord(board,word,index+1,newX,newY):
return True

self.visit[startX][startY] = False
return False


else:
return False




s = Solution()

board =[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]



word = "ABCCED"

print s.exist(board,word)

猜你喜欢

转载自www.cnblogs.com/lux-ace/p/10556996.html