剑指offer面试题12(java版):矩阵中的路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/littlehaes/article/details/91384714

welcome to my blog

剑指offer面试题12(java版):矩阵中的路径

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

思路

见注释

复杂度

  • 时间复杂度:O(n^3)?
  • 空间复杂度:O(n)
public class Solution {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {   // 标志位:表示matrix当前坐标是否可以到达,初始全为true,表示都可以到达  
        boolean[] flag =  new boolean[matrix.length];
        for(int i=0; i<flag.length; i++)
            flag[i]=true;
        // 逐个以matrix的元素为路径起点进行回溯搜索
        for(int i=0; i<rows; i++)
            for(int j=0; j<cols; j++){
                if(recallMethod(matrix, rows, cols, i, j, str, 0, flag))
                    return true;
            }
        // 调出循环说明没有这样的路径,返回false
        return false;
    }
    // i,j分别为matrix的行坐标和纵坐标,从0开始
    // char_index表示str中char的索引
    public boolean recallMethod(char[] matrix, int rows, int cols, int i, int j, char[] str, int char_index, boolean[] flag){
        // 将二维坐标转换为一维坐标
        int index = i*cols + j;
        // 搜索失败,返回false的情况: i,j坐标越界;(i,j)表示的元素跟str[char_index]不同;(i,j)位置不可到达
        if(i<0 || i >=rows || j<0 || j>=cols || matrix[index]!=str[char_index] || flag[index]==false)
            return false;
        // 跳过上面的if,说明当前matrix[index]==str[char_index]; 如果char_index是str的末尾,说明路径匹配完毕,返回true; 否则需要判断(i,j)的上下左右是否和str[char_index+1]相同
        // 
        if(char_index == str.length-1)
            return true; // 这个true是最关键的,代表找到了匹配的路径
        // 搜索下一个点时,当前点就不能访问了
        flag[index]=false;
        if(recallMethod(matrix, rows, cols, i+1, j, str, char_index+1, flag) ||
          recallMethod(matrix, rows, cols, i-1, j, str, char_index+1, flag) ||
           recallMethod(matrix, rows, cols, i, j+1, str, char_index+1, flag) ||
           recallMethod(matrix, rows, cols, i, j-1, str, char_index+1, flag))
            return true;
        // 执行到这里表示(i,j)的上下左右点都不满足条件,这个点还能访问,重新表为true
        // 但是从这个点往下匹配不到路径了,返回false,向上回溯
        flag[index]=true;
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/littlehaes/article/details/91384714