Offer surface prove safety questions 12 (java version): The channel matrix

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91384714

welcome to my blog

Offer surface prove safety questions 12 (java version): The channel matrix

Title Description

Please design a function that determines whether there is a route that contains all the characters of a character string in a matrix. A lattice path may start from any of the matrix, each step in the matrix can be left, right, up, down one grid. If one path through the matrix of one grid, the following can not enter the grid again. Such abcesfcsadee e.g. 3 X 4 matrix containing the path "bcced" in a string, but does not contain the matrix "abcb" path, since the first character string occupies the first row of the matrix b in the second lattice after that, the path can not enter the grid again.

Thinking

See note

the complexity

  • Time complexity: O (n ^ 3)?
  • Space complexity: 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;
    }
}

Guess you like

Origin blog.csdn.net/littlehaes/article/details/91384714