当前位置:网站首页>79. 单词搜索【dfs + 回溯visit + 遍历起点】
79. 单词搜索【dfs + 回溯visit + 遍历起点】
2022-07-01 12:35:00 【白速龙王的回眸】

分析
用dfs + visit + 回溯的思路
然后找到合适的入口
再看看下一个上下左右的位置拿个是适合放的(这里用visit回溯)
dfs遍历所有能走的位置,只要有一个子dfs返回True
那么整个就是True的,如果没有返回True
很遗憾,那只能是False
最后如果能去到最后一个位置即可返回
ac code
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
m, n = len(board), len(board[0])
k = len(word)
# dfs + 回溯
def dfs(r, c, idx):
if idx == k - 1:
return True
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < m and 0 <= nc < n and word[idx + 1] == board[nr][nc] and visit[nr][nc] is False:
visit[nr][nc] = True
temp = dfs(nr, nc, idx + 1)
if temp: return True
visit[nr][nc] = False
return False
# 遍历每个起点
for i in range(m):
for j in range(n):
visit = [[False] * n for _ in range(m)]
if board[i][j] == word[0]:
visit[i][j] = True
if dfs(i, j, 0): return True
return False
总结
dfs的参数记录当前的位置以及当前的已放的最后一个元素的idx
成功条件就是到达最后一个索引
边栏推荐
- Eurake分区理解
- Fatal error: execution: there is no such file or directory
- Indefinite integral
- Good luck brought by years of persistence
- Four years after graduation: work, resign, get married, buy a house
- Sleep quality today 79 points
- BIM and safety in road maintenance-buildSmart Spain
- 木架的场景功能
- Huawei interview question: Recruitment
- 被锡膏坑了一把
猜你喜欢

Sleep quality today 79 points

Stack-------

Operations related to sequence table

【datawhale202206】pyTorch推荐系统:多任务学习 ESMM&MMOE

Onenet Internet of things platform - mqtts product equipment connected to the platform

Share several tools for designing exquisite circuit diagrams

Indefinite integral

晓看天色暮看云,美图欣赏

Onenet Internet of things platform - mqtt product devices send messages to message queues MQ

Four years after graduation: work, resign, get married, buy a house
随机推荐
Blue Bridge Cup multi interface switching processing (enumeration plus state machine method)
Onenet Internet of things platform - the console sends commands to mqtt product devices
2022-06-28-06-29
"Analysis of 43 cases of MATLAB neural network": Chapter 40 research on prediction of dynamic neural network time series -- implementation of NARX based on MATLAB
Nc100 converts strings to integers (ATOI)
Understanding of NAND flash deblocking
BIM and safety in road maintenance-buildSmart Spain
JS reverse | m3u8 data decryption of a spring and autumn network
单点登录SSO与JWT好文整理
QT 播放器之列表[通俗易懂]
Onenet Internet of things platform - mqtt product devices send messages to message queues MQ
[datawhale202206] pytorch recommendation system: recall model DSSM & youtubednn
Relationship between accuracy factor (DOP) and covariance in GPS data (reference link)
MySQL data table creation
被锡膏坑了一把
BIM and safety in road maintenance-buildSmart Spain
ASP. Net core 6 from entry to enterprise level practical development application technology summary
One year anniversary of bitbear live studio, hero rally order! I invite you to take a group photo!
使用nvm管理nodejs(把高版本降级为低版本)
MySQL common functions