当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

ES6 从入门到精通 # 14:迭代器 Iterator 的用法

Eureka protects itself

JVM Memory and Garbage Collection - 10. Direct Memory

【集训DAY5】选数字【数学】

数字孪生智慧制造生产线项目实施方案,平台认知与概念

【集训DAY4】异或【字典树】

天猫全网商品详情封装接口

The older tester has just passed the "hurdle" of being 35 years old, and I want to tell you something from my heart

【SSL集训DAY2】有趣的数【数位DP】

Creo5.0入门教程赠素材
随机推荐
Why don't suggest you run in Docker Mysql?
ECCV 2022 | 微软开源TinyViT :搞定小模型的预训练能力
阿里云短信服务开通
NTP SERVICE TASK 在GWserver配置、启用NTP服务,为当前环境提供时钟同步服务,Client主机可以从该服务器同步时间。
漫谈缺陷管理的自动化实践方案
【集训DAY5】堆箱子【数学】
《MySQL入门很轻松》第4章:数据表中存放的数据类型
【猜凶手,猜名次,杨辉三角】经典小学奥数的代码逻辑是什么?
Project (7) - PolarSeg point cloud semantic segmentation
游泳馆系统次卡的设置有哪些细节?
【渗透工具】浏览器数据导出工具
Wireshark classic practice and interview 13-point summary
ES6 从入门到精通 # 13:数组的扩展方法二
JSON对象和字符串相互转化
WPF DataGrid using data templates
Service Discovery @EnableDiscoveryClient
【集训DAY5】选数字【数学】
Golden Warehouse Database KingbaseGIS User Manual (6.6. Geometric Object Verification Function, 6.7. Spatial Reference System Function)
源码编译安装LAMP和LNMP
【SSL集训DAY2】有趣的数【数位DP】