The sword refers to the offer - the path in the matrix

Please design a function to determine whether there is a path containing all characters of a string in a matrix. The path can start from any cell in the matrix, and each step can move one cell left, right, up, and down in the matrix. If a path passes through a grid in the matrix, the path can no longer enter that grid. For example, the abcsfcsadee matrix contains a path to the string "bcced", but the matrix does not contain the path "abcb", because the first character b of the string occupies the first row of the matrix. After the second grid, the path cannot be repeated enter this grid.

understand:

This question has almost the same idea as the question "The range of motion of the robot". Focus the problem on each letter, and you can traverse and solve the problem after dealing with one .
In comparison, this question is a little more complicated because the starting point is not fixed. Because the starting point is not fixed, the starting point is traversed in hasPath , and two for loops are used to nest; the flag array is also defined in hasPath .
Put the process of recursive scanning into hasPathCore for processing, and let the termination condition come first, so pay attention to the order of the three ifs. First, the search fails to perform false fallback, the second is the final true return when the search is successful, and the last is General recursive process.
It should be noted that the last flag[index] = 0; if it is not scanned, the starting point will be released and the flag will be cleared.

public class Solution {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {
        int[] flag = new int[matrix.length];
        for(int r = 0; r < rows; r++){
            for(int c = 0; c < cols; c++){
                if(hasPathCore(matrix, rows, cols, r, c, str, 0, flag)){
                    return true;
                }
            }
        }
        return false;
    }

    private boolean hasPathCore(char[] matrix, int rows, int cols, int r, int c, char[] str, int k, int[] flag){
        int index = r*cols+c;
        if(r < 0 || r >= rows || c < 0 || c >= cols || matrix[index] != str[k] || flag[index] == 1){
            return false;
        }

        if(k == str.length-1){  //三个if 的顺序很重要,直接决定了功能的递归实现
            return true;
        }
        flag[index] = 1;

        if(hasPathCore(matrix,rows,cols,r+1,c,str,k+1,flag)
          || hasPathCore(matrix,rows,cols,r-1,c,str,k+1,flag)
          || hasPathCore(matrix,rows,cols,r,c+1,str,k+1,flag)
          || hasPathCore(matrix,rows,cols,r,c-1,str,k+1,flag)){
            return true;
        }
        flag[index] = 0;
        return false;

    }

}









Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325378017&siteId=291194637