博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
算法-矩阵中的路径2
阅读量:3959 次
发布时间:2019-05-24

本文共 1855 字,大约阅读时间需要 6 分钟。

public class Solution {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str){
boolean[] flag = new boolean[matrix.length]; for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(judge(matrix, rows, cols, i, j, str, 0, flag)) {
return true; } } } return false; } //matrix一维数组 rows矩阵的行 cols矩阵的列, 该点所在当前位置的行和列rowIndex colIndex str要寻找的字符串 k字符串的那个位置,flag该点有没有下过 public boolean judge(char[] matrix, int rows, int cols, int rowIndex, int colIndex, char[] str, int k, boolean[] flag) {
//获取该点在一维数组中的位置 int index = rowIndex * cols + colIndex; //该点越界直接false if(rowIndex < 0 || rowIndex > rows - 1 || colIndex < 0 || colIndex > cols - 1) {
return false; } //如果没有越界,该点还在矩阵中 //1.该点不等于对应字符串的点false if(matrix[index] != str[k]) {
return false; } //2.该点走过false if(flag[index] == true) {
return false; } //3.该点有没有下过,又相等 //3.1该点是字符串对应最后一个 if(k == str.length - 1) {
//直接true return true; } //3.2该点不是最后一个,先记录该点下过,怕等下递归的时候往回找 flag[index] = true; //3.3递归 boolean ans = judge(matrix, rows, cols, rowIndex + 1, colIndex, str, k + 1, flag) || judge(matrix, rows, cols, rowIndex - 1, colIndex, str, k + 1, flag) || judge(matrix, rows, cols, rowIndex, colIndex - 1, str, k + 1, flag) || judge(matrix, rows, cols, rowIndex, colIndex + 1, str, k + 1, flag); if(ans == true) {
return true; }else {
flag[index] = false;//该点走不到终点,标记该点没走过,下次递归的时候该点还是可以走的 return false; } }}

转载地址:http://ivhzi.baihongyu.com/

你可能感兴趣的文章
回文题
查看>>
AJAX应用之注册用户即时检测
查看>>
File 类小结
查看>>
java除去字符串空格
查看>>
jsp 2.0标记文件
查看>>
Hibernate中Criteria的完整用法
查看>>
sql jsp
查看>>
spring beans beanfactory applicationcontext
查看>>
使用ORM工具进行数据访问
查看>>
使用ORM工具进行数据访问
查看>>
编译与部署Eclipse+Tomcat+MySQL+Liferay4.1.2
查看>>
POJ3728,The merchant(倍增LCA+分治)
查看>>
2019 ICPC Malaysia National,E. Optimal Slots(01背包变形)
查看>>
洛谷P1638 逛画展(双向队列)
查看>>
POJ2892,Tunnel Warfare(线段树维护连续区间)
查看>>
POJ3468,A Simple Problem with Integers(线段树-区间查询-区间更新)
查看>>
杭电ACM——6463(思维)
查看>>
杭电ACM——2069,Coin Change(DP)
查看>>
杭电ACM——2110,Crisis of HDU(母函数)
查看>>
杭电AM——2152,Fruit(母函数)
查看>>