问题
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
solution
- 深度遍历:找到可能的起点利用递归进行遍历
- 遍历后的点需要添加一个标签:这里需要用到回溯的思想
- 然后原来是尝试完所有输出,这样的时间复杂度始终1为最坏情况的时间。后面修改成了,知道找到一条路为True则直接返回。
代码如下:
import copy
def find_road(st,word,board,i,visited):
# print(i,st, board[st[0]][st[1]])
if i>= len(word):
return True
if board[st[0]][st[1]] != word[i]:
return False
if i == len(word)-1:
return board[st[0]][st[1]] == word[i]
visited[st[0]][st[1]]=1
final = False
if st[1]-1>=0 and visited[st[0]][st[1]-1]==0:
if (find_road([st[0],st[1]-1],word,board,i+1,visited)):return True
# print(visited,st)
if (st[1]+1)<len(board[0]) and visited[st[0]][st[1]+1]==0:
if (find_road([st[0],st[1]+1],word,board,i+1,visited)):return True
if st[0]-1>=0 and visited[st[0]-1][st[1]]==0:
if (find_road([st[0]-1,st[1]],word,board,i+1,visited)):return True
if st[0]+1<len(board) and visited[st[0]+1][st[1]]==0:
if (find_road([st[0]+1,st[1]],word,board,i+1,visited)):return True
visited[st[0]][st[1]]=0
return False
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
m = len(board)
n = len(board[0])
if m==1 and n==1 and len(word)==1:
return board[0][0]==word[0]
## 建立栈进行深度遍历
stack = []
for i in range(m):
for j in range(n):
if board[i][j]==word[0]:
stack.append([i,j])
### 开始遍历
res = False
for st in stack:
visited=[[0]*n for _ in range(m)]
res =res or find_road(st,word,board,0,visited)
if res == True:
break
return res
```