回溯法-矩阵中的路径

判断矩阵中有没有给出的路径。
例如:
‘a’,‘b’,‘c’,‘e’,
‘s’,‘f’,‘c’,‘s’,
‘a’,‘d’,‘e’,‘e’
矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子,也就是说每一个字符只能使用一次。
Tip:如果看到“每一个字符/数字只能使用一次”,就考虑加一个布尔数组记录每个元素是否被访问过。
思路:

  1. .写寻找路径的方法:
    hasPath(矩阵,目标路径,矩阵行坐标,矩阵列坐标,目标路径当前位置,矩阵行数,矩阵列数,访问数组){
    ---- IF(当前坐标元素在矩阵内部 && 未被访问过 && 与路径当前位置的元素相等){
    -------------当前坐标设置为已访问;
    -------------目标路径当前位置向后移动一位;
    -------------在该坐标的上、下、左、右四个方向寻找移动后的位置;
    -------------if(未找到){
    ------------------- 目标路径回到原来位置;
    ------------------- 当前坐标恢复为未访问;
    ----------}
    -----}
    if(目标路径当前位置==目标路径长度)成功结束;
    失败,返回false;
    }

  2. 遍历矩阵,寻找路径,如果存在路径:
    if(递归结果为true)返回true;否则,false

这题需要注意的:
矩阵用一个一维数组表示的,所以我们如果用(r,c)坐标定位一个元素的话:matrix[ r*行数+c]
这样方便在上下左右四个位置进行定位搜索;

public static boolean hasPath(char[] matrix, int rows, int cols, char[] str){
        boolean[] visited=new boolean[rows*cols];
        int len=str.length;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if( hasPathHelper(visited,matrix,rows,cols,i,j,str,0))
                    return true;
            }
        }
        return false;
    }
    public static boolean hasPathHelper(boolean[] visited,char[] matrix, int rows, int cols,int r,int c, char[] str,int start){
       boolean hasPath=false;
        if (start==str.length) return true;
        if (r>=0 && r<rows && c>=0 && c<cols && visited[r*cols+c]==false && matrix[r*cols+c] == str[start]) {
            visited[r*cols+c] = true;
            start++;
            hasPath= hasPathHelper(visited, matrix, rows, cols, r + 1, c, str, start) ||
                    hasPathHelper(visited, matrix, rows, cols, r - 1, c, str, start) ||
                    hasPathHelper(visited, matrix, rows, cols, r, c + 1, str, start) ||
                    hasPathHelper(visited, matrix, rows, cols, r, c - 1, str, start);
            if (hasPath==false) {
                start--;
                visited[r*cols+c]=false;
            }
        }
        return hasPath;
    }

版权声明:本文为weixin_44104102原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。