当前位置:网站首页>【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;
}
}
边栏推荐
- nfs服务部署笔记
- SAR成像之点目标仿真(一)—— 数学模型
- PostgreSQL k8s deployment template
- Rhcsa - - parcourir le contenu du fichier, couper, uniq, trier, utiliser les commandes.tr
- PPP configuration instance learning record
- CORTEX-A系列处理器
- C # enter a letter and judge its case
- 使用vscode进行远程编辑和调试
- In the Internet era, how to refine user operations?
- Numpy:基本操作快速入门
猜你喜欢

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

Confused, work without motivation? Career development hopeless? It's enough to read this article

ZABBIX monitoring detailed installation to deployment

HCIA----05 RIP

HCIA----07 ACL-Net

Jupyter notebook添加已存在的虚拟环境

在GPU上运行MATLAB程序

Redis如何实现持久化?详细讲解RDB的三种触发机制及其优缺点,带你快速掌握RDB

快速解决:Xshell拖不进去文件夹或者软件包的问题

Frame relay network configuration example learning record
随机推荐
常见的cmd命令快速打开程序
Desensitize data
高压MOS管KNX42150 1500V/3A 应用于变频器电源-逆变器等
Li Kou 729. My schedule I
将集合使用流进行分页
静态扩展配置
基于redis+lua进行限流
Cortex-a series processor
Redis distributed lock practice
设计思维的“布道者”
OSPF实验
Pod topology constraints
HCIA----02
软件测试岗位饱和了?自动化测试是新一代‘offer’技能
转行软件测试有学历要求吗?低于大专是真的没出路吗?
Common scheduled cron expressions for scheduled tasks
雷达导论PART VII.2 成像方法
2020-09-22
C output Fibonacci sequence
将指定秒转为时分秒格式