题目:79. Word Search
题目链接:https://leetcode.com/problems/word-search/description/
大致意思呢,是给定一个二维数组,每个元素均是一个字母,要求在数组中寻找给定的字符串,每个元素只能使用一次。如果能找到返回True,否则返回False。例如:
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
当目标字符串为"SEE"时,可以在数组中找到(右下角三个组成SEE),返回True。
可以用DFS来写,中间搜索过程中抛弃超过指定字符串长度的分支,找到一个结果返回即可。
Python:
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
self.res = False
def cango(x,y,rows,cols):
return x>=0 and x<rows and y>=0 and y<cols
rows=len(board)
cols=len(board[0])
direct=[(0,1),(1,0),(0,-1),(-1,0)]
vis=set()
def dfs(target,board,x,y,step,path):
vis.add((x,y))
if step==len(target) and path==target:
self.res=True
return
if step>len(target):
return
for i in range(4):
if self.res==True:
return
nx,ny=x+direct[i][0],y+direct[i][1]
if cango(nx,ny,rows,cols) and (nx,ny) not in vis and board[nx][ny]==target[step]:
dfs(target,board,nx,ny,step+1,path+board[nx][ny])
vis.remove((nx,ny))
for i in range(rows):
for j in range(cols):
if board[i][j]==word[0]:
vis.clear()
self.res=False
dfs(word,board,i,j,1,''+word[0])
if self.res==True:
return True
return False