您的位置:首页 > 其它

LeetCode-79-Word Search 爆搜

2017-09-27 15:31 459 查看
class Solution(object):
d=[[1,0],[0,1],[-1,0],[0,-1]]
used=[]
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
Lenx=len(board)
if Lenx==0:return False
if len(word)==0:return True
Leny=len(board[0])
for i in range(Lenx):
for j in range(Leny):
if board[i][j]==word[0]:
self.used=[[0 for x in range(Leny)]for y in range(Lenx)]
if self.dfs(i,j,word[1:],Lenx,Leny,board):return True
return False

def dfs(self,x,y,word,Lenx,Leny,board):
#print word
self.used[x][y]=1
if word=="":return True
for i in range(4):
newx=x+self.d[i][0]
newy=y+self.d[i][1]
#print newx,newy
if newx>=0 and newx<Lenx and newy>=0 and newy<Leny and self.used[newx][newy]==0 and board[newx][newy]==word[0]:
if self.dfs(newx,newy,word[1:],Lenx,Leny,board):
return True
self.used[newx][newy]=0
return False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: