【算法题】矩阵中的路径

题目描述
在这里插入图片描述

分析
利用回溯法,从矩阵任一点开始,向四周试探,若满足字符顺序,则走一步并继续试探,直到字符串搜索结束返回true。如果都不满足,则回溯继续搜索。由于不能重复走同一个格子,需要一个额外的布尔数组记录走过的路径,同时,在回溯时要将走过的当前格子标记清除。

代码(已AC)

public class Solution {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {
        boolean[] flags = new boolean[matrix.length];
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                if(judge(matrix,i,j,rows,cols,str,0,flags)) return true;
            }
        }
        return false;
    }
    public boolean judge(char[] matrix,int i, int j, int rows, int cols, char[] str, int idx, boolean[] flags){
        int index = i*cols+j;
        if(i<0 || j<0 || i>=rows || j>=cols || flags[index] || matrix[index]!=str[idx]) return false;
        if(idx == str.length-1) return true;
        flags[index] = true;
        if( judge(matrix, i+1, j, rows, cols, str, idx+1, flags) ||
            judge(matrix, i-1, j, rows, cols, str, idx+1, flags) ||
            judge(matrix, i, j+1, rows, cols, str, idx+1, flags) ||
            judge(matrix, i, j-1, rows, cols, str, idx+1, flags))
            return true;
        flags[index] = false;   // 回溯
        return false;
    }
}
原创文章 28 获赞 22 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Steven_L_/article/details/105920116