剑指offer 66题 【回溯法】矩阵中的路径

来源:互联网 发布:ubuntu jdk1.7 安装 编辑:程序博客网 时间:2024/05/09 09:06

题目描述

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

牛客传送门:点击打开链接

public class Title66 {int row,col,i,j,index;int[] access;public boolean hasPath(char[] matrix, int rows, int cols, char[] str){if(matrix == null || rows <=0 || cols <=0)return false;row = rows;col = cols;access = new int[matrix.length];for(int i=0;i<row;i++){for(int j=0;j<col;j++){if(matrix[i*col + j] == str[0]){if(hasPath(matrix,str,i,j,1))return true;}}}return false;    }public boolean hasPath(char[] matrix, char[] str,int i,int j,int index){    if(index == str.length)    return true;    access[i*col+j] = 1;boolean left,right,up,down;left = right = up = down = false;if(check(i-1,j) && access[(i-1)*col+j] == 0 && matrix[(i-1)*col+j] == str[index])    up = hasPath(matrix,str,i-1,j,index+1);if(check(i+1,j) && access[(i+1)*col+j] == 0 && matrix[(i+1)*col+j] == str[index])    down = hasPath(matrix,str,i+1,j,index+1);if(check(i,j-1) && access[i*col+j-1] == 0 && matrix[i*col+j-1] == str[index])    left = hasPath(matrix,str,i,j-1,index+1);if(check(i,j+1) && access[i*col+j+1] == 0 && matrix[i*col+j+1] == str[index])    right = hasPath(matrix,str,i,j+1,index+1);access[i*col+j] = 0;return up || down || left || right;    }public boolean check(int i,int j){if(i < 0 || i >= row || j < 0 || j >= col)return false;return true;}public static void main(String[] args) {// "ABCESFCSADEE",3,4,"SEE"// "ABCESFCSADEE",3,4,"ABCB"char[] matrix = "abcesfcsadee".toCharArray();Title66 clazz = new Title66();System.out.println(clazz.hasPath(matrix, 3, 4, "bcced".toCharArray()));System.out.println(clazz.hasPath(matrix, 3, 4, "abcd".toCharArray()));System.out.println(clazz.hasPath(matrix, 3, 4, "see".toCharArray()));System.out.println(clazz.hasPath(matrix, 3, 4, "abcb".toCharArray()));}}

0 0
原创粉丝点击