当前位置:网站首页>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
成功条件就是到达最后一个索引
边栏推荐
- BIM and safety in road maintenance-buildSmart Spain
- Double linked list related operations
- Zero copy technology of MySQL
- Understanding of NAND flash deblocking
- Chain storage of binary tree
- 网络socket的状态要怎么统计?
- R语言基于h2o包构建二分类模型:使用h2o.gbm构建梯度提升机模型GBM、使用h2o.auc计算模型的AUC值
- GPS 数据中的精度因子(DOP)与协方差之间的关系 (参考链接)
- Machine learning - Data Science Library Day 3 - Notes
- ROS2 Foxy depthai_ros教程
猜你喜欢

The operation process of using sugar to make a large data visualization screen

ROS2 Foxy depthai_ros教程

Typora realizes automatic uploading of picture pasting

Typora adds watermarks to automatically uploaded pictures

I wish you all a happy reunion

【邂逅Django】——(二)数据库配置

How to use opcache, an optimization acceleration component of PHP

队列操作---

Onenet Internet of things platform - create mqtts products and devices

Onenet Internet of things platform - mqtt product devices send messages to message queues MQ
随机推荐
【邂逅Django】——(二)数据库配置
Huawei interview question: Recruitment
ASTM D 3801 vertical burning test of solid plastics
【20211129】Jupyter Notebook远程服务器配置
2022-06-28-06-29
CPI tutorial - asynchronous interface creation and use
Sleep quality today 79 points
数论基础及其代码实现
List of QT players [easy to understand]
二叉树的链式存储
Operations related to sequence table
Blue Bridge Cup multi interface switching processing (enumeration plus state machine method)
Machine learning - Data Science Library - day two
Tencent Li Wei: deeply cultivate "regulatory technology" to escort the steady and long-term development of the digital economy
Circular linked list--
MySQL data table creation
Application of stack -- bracket matching problem
Double linked list related operations
Arm GIC (V) how arm TrustZone supports security interrupt analysis notes.
本科毕业四年:工作,辞职,结婚,买房