当前位置:网站首页>【JZOF】12矩阵中的路径
【JZOF】12矩阵中的路径
2022-07-23 05:56:00 【叹了口丶气】

典型的DFS算法的题:
分上下左右四个方向,进行搜索。
搜索前把搜索的位置标记一下
import java.util.*;
public class Solution {
public boolean hasPath(char[][] matrix, String word) {
char[] words = word.toCharArray();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
//从[i,j]这个坐标开始查找
if (dfs(matrix, words, i, j, 0))
return true;
}
}
return false;
}
boolean dfs(char[][] matrix, char[] word, int i, int j, int index) {
//边界的判断,如果越界直接返回false。index表示的是查找到字符串word的第几个字符,
//如果这个字符不等于matrix[i][j],说明验证这个坐标路径是走不通的,直接返回false
if (i >= matrix.length || i < 0 || j >= matrix[0].length || j < 0 || matrix[i][j] != word[index])
return false;
//如果word的每个字符都查找完了,直接返回true
if (index == word.length - 1)
return true;
//把当前坐标的值保存下来,为了在最后复原
char tmp = matrix[i][j];
//然后修改当前坐标的值
matrix[i][j] = '.';
//走递归,沿着当前坐标的上下左右4个方向查找
boolean res = dfs(matrix, word, i + 1, j, index + 1)
|| dfs(matrix, word, i - 1, j, index + 1)
|| dfs(matrix, word, i, j + 1, index + 1)
|| dfs(matrix, word, i, j - 1, index + 1);
//递归之后再把当前的坐标复原
matrix[i][j] = tmp;
return res;
}
}
边栏推荐
猜你喜欢

基于redis+lua进行限流

Unity 模型显示到UI前面,后面的UI抖动

Ronge answer script production (latest in 2020)

Static route configuration instance learning record

ACL——net

How does redis implement persistence? Explain in detail the three triggering mechanisms of RDB and their advantages and disadvantages, and take you to quickly master RDB

雷达导论PART VII.4 SAR系统设计

ACL访问控制实验

录入数学公式至mark down文档的方法

HCIA----05 RIP
随机推荐
TI单芯片毫米波雷达1642代码走读(〇)——总纲
Signal integrity (SI) power integrity (PI) learning notes (32) power distribution network (4)
HCIA----04 路由静态扩展、VLAN
Redis distributed lock practice
FTP deployment
雷达导论PART VII.1 雷达与分辨率
linx的链接、一级目录、重定向、cp与mv
踩坑electron渲染进程renderer,解决require is not defined的问题
numpy:矩阵的元素选取
动态RIP配置
Common scheduled cron expressions for scheduled tasks
JVM内存模型简介
redis分布式锁实践
高压MOS管KNX42150 1500V/3A 应用于变频器电源-逆变器等
Step on the electric render process renderer to solve the problem of require is not defined
快速解决:Xshell拖不進去文件夾或者軟件包的問題
Helm installing rancher
Signal integrity (SI) power integrity (PI) learning notes (XXXI) power distribution network (III)
User and group management, file permissions
Unity 模型显示到UI前面,后面的UI抖动