当前位置:网站首页>剑指offer 矩阵中的路径
剑指offer 矩阵中的路径
2022-07-19 05:02:00 【*^O^*—*^O^*】
题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如
矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
题目链接
解题思路
首先二维数组遍历,就可以想到使用搜索了,这个题目需要一步一步的匹配,就是后面的匹配成功了,前面的肯定是正确的,所以使用深度优先搜索。首先我们弄一个数组表示四个方向,从找到的第一个字符开始,依次往后查找,这里为了防止往回查找,就需要来一个一样大小的二维数组作为标记,要是可以就返回真,不行就直接下一个,就这样遍历完了之后,若是记录字符串的指针指到最后一个字符,那就返回真。
代码示例
import java.util.*;
public class Solution {
private int[][] dir = new int[][]{
{
0, 1}, {
0, -1}, {
1, 0}, {
-1, 0}};
public boolean hasPath (char[][] matrix, String word) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[0].length; j++) {
boolean[][] vis = new boolean[matrix.length][matrix[0].length];
if(dfs(matrix, word, i, j, vis, 0)) {
return true;
}
}
}
return false;
}
public boolean dfs(char[][] matrix, String word, int i, int j, boolean[][] hasVisted, int index) {
if(word.length() == index) {
//第一次进入到这里,就是第一个字符匹配,
//那要是这个字符就是最后一个字符,就可以直接返回true了
return true;
}
if(i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length
|| hasVisted[i][j] || word.charAt(index) != matrix[i][j]) {
return false;
}
hasVisted[i][j] = true;
for(int[] d : dir) {
if(dfs(matrix, word, i + d[0], j + d[1], hasVisted, index + 1)) {
return true;//只要有一个满足就可以了.就可以返回了
}
}
//没有一个满足,就改回去,顺便返回
hasVisted[i][j] = false;
return false;
}
}
边栏推荐
猜你喜欢
接口测试主要测试哪方面?需要哪些技能?要怎么学习?
开发提测标准(简易版)
[signal conditioning] sharing practical experience of building CE amplifier with "crystal triode"
Redis地理算法GEO解析和应用
How to debug the dynamic code generated by C emit?
四剑客与Code Review的恩怨情仇:“始乱终弃”到“浪子回头”
Next time, the interviewer will ask about the design of high concurrency system and directly dump this article to him
Hc-sr04 ultrasonic module driven by 51 single chip microcomputer (LCD1602 display)
Opencv image processing --------- environment installation configuration
编译器除法优化
随机推荐
. Net full scene development has finally arrived
下次面试官再问高并发系统设计,直接把这篇文章甩给他
nodejs面经
swing窗体打jar包后找不到图片的问题
Rllib学习[2] --env定义 + env rollout
Redis地理算法GEO解析和应用
three. JS endless pipeline Perspective
Spiderpi convenient operation manual
Mysql千万级别水平分表优化
C Foundation (II)
Rookie teaches you to repair USB flash disk
Kalman filter ultrasonic ranging
接口测试主要测试哪方面?需要哪些技能?要怎么学习?
An open source web drawing board is really convenient
JWT(JSON Web Token)的基础使用
Upgrade the pit stepped in php8
Where is Jay Chou's album "the greatest work"? Dangbei box enjoys chairman Zhou's latest MV
C # use objects comparer to compare objects
提交时显示找不到匹配的主机密钥类型。
那些年微信支付踩过的坑