当前位置:网站首页>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
成功条件就是到达最后一个索引
边栏推荐
猜你喜欢

I wish you all a happy reunion

Circular linked list--

Common chart usage of Bi tools

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

VS Code 设置代码自动保存

队列操作---

Arm GIC (V) how arm TrustZone supports security interrupt analysis notes.

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

本科毕业四年:工作,辞职,结婚,买房
![[20211129] configuration du serveur distant du carnet de notes jupyter](/img/7c/79c9fcb91bde75e954dc3ecf9f5afd.png)
[20211129] configuration du serveur distant du carnet de notes jupyter
随机推荐
I wish you all a happy reunion
二叉树的链式存储
R语言使用yardstick包的conf_mat函数计算多分类(Multiclass)模型在每个交叉验证(或者重采样)的每一折fold上的混淆矩阵、并使用summary输出每个fold的其它详细指标
硬阈值(Hard Thresholding)函数解读[通俗易懂]
2022-06-28-06-29
[Suanli network] technological innovation of Suanli Network -- key technology of operation service
Ipv6-6to4 experiment
List of QT players [easy to understand]
单点登录SSO与JWT好文整理
晓看天色暮看云,美图欣赏
localtime居然不可重入,踩坑了
(mixed version 1) multiple TXT text to one table
MySQL common functions
腾讯安全联合毕马威发布监管科技白皮书,解析“3+3”热点应用场景
【datawhale202206】pyTorch推荐系统:召回模型 DSSM&YoutubeDNN
Wechat applet - 80 practical examples of wechat applet projects
Relationship between accuracy factor (DOP) and covariance in GPS data (reference link)
Ansible相关内容梳理
[brain opening] west tide and going to the world series
Understanding of NAND flash deblocking