当前位置:网站首页>Leetcode79. 单词搜索
Leetcode79. 单词搜索
2022-08-09 23:32:00 【Java全栈研发大联盟】
题目传送地址: https://leetcode.cn/problems/word-search/submissions/
运行效率:
代码如下:
//回溯法,递归
public static boolean exist(char[][] board, String word) {
HashSet<String> set = new HashSet<>();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == word.charAt(0)) {
if (recur(i, j, board, word, 0, set)) {
return true;
}
}
}
}
return false;
}
//注意要在recur函数的开头set.add(row + ":" + col); 且在结尾要 set.remove(row + ":" + col); 这才是回溯的状态的还原
public static boolean recur(int row, int col, char[][] board, String word, int k, HashSet<String> set) {
//处理边界情况
if (k == word.length() - 1) {
if (board[row][col] == word.charAt(k)) {
set.add(row + ":" + col);
return true;
}
return false;
}
if (board[row][col] != word.charAt(k)) {
return false;
}
//当前坐标的元素能不能成为贪吃蛇的蛇头, 取决于左、右、下 三个位置的情况
boolean bottom;
boolean left;
boolean right;
boolean top;
set.add(row + ":" + col);
boolean result = false;
//下边相邻的坐标
if (row + 1 < board.length && !set.contains((row + 1) + ":" + col)) {
bottom = recur(row + 1, col, board, word, k + 1, set);
if (bottom) {
result = true;
}
}
//左边相邻的坐标
if (col - 1 >= 0 && !set.contains(row + ":" + (col - 1))) {
left = recur(row, col - 1, board, word, k + 1, set);
if (left) {
result = true;
}
}
//右边相邻的坐标
if (col + 1 < board[0].length && !set.contains(row + ":" + (col + 1))) {
right = recur(row, col + 1, board, word, k + 1, set);
if (right) {
result = true;
}
}
//上边相邻的坐标
if (row - 1 >= 0 && !set.contains((row - 1) + ":" + col)) {
top = recur(row - 1, col, board, word, k + 1, set);
if (top) {
result = true;
}
}
set.remove(row + ":" + col);
return result;
}
边栏推荐
- 深度剖析 Apache EventMesh 云原生分布式事件驱动架构
- 拒绝“重复造轮子”,百度EasyDL让你玩转AI定制开发
- ES6 Beginner to Mastery #13: Extension Methods for Arrays 2
- The older tester has just passed the "hurdle" of being 35 years old, and I want to tell you something from my heart
- 知行合一的时候
- nfs配置
- AUTOCAD——形位公差如何标注、CAD打断于点的操作
- C语言学习之旅 【操作符(残缺版)】
- JSP简介
- dlopen failed: library "libtaml.so" not found
猜你喜欢
随机推荐
蔚来杯2022牛客暑期多校训练营7 CFGJ
字节技术面都过了,薪资都谈好了20K*13结果还是被刷了,问HR原因是。。。
YOLOV5学习笔记(七)——训练自己数据集
Linux安装Oracle和postgrepSQL数据库
framework源码读后感
生成树和交换的总结
ES6 从入门到精通 # 14:迭代器 Iterator 的用法
解锁时间生成与比较
服装店管理系统如何推送活动?
New window Display Agreement
【集训DAY5】堆箱子【数学】
聚焦热点 | ISC 2022软件供应链安全治理与运营论坛圆满落幕
拼多多店铺运营不得不知的留个运营小知识
【obs】obsqsv11 硬编 及与metartc codec对比
The technical aspects of the byte have been passed, and the salary has been negotiated for 20K*13, but the result is still being brushed. I asked the HR why...
拒绝“重复造轮子”,百度EasyDL让你玩转AI定制开发
南大通用数据库-Gbase-8a-学习-04-部署分布式集群
JSP简介
【C语言】通讯录《静态内存版本》
共创 Ray 中文社区,Ray Forward Meetup 2022 直播邀你参加!