请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如[a b c e s f c s a d e e]是3*4矩阵,其包含字符串"bcced"的路径,但是矩阵中不包含“abcb”路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
直接用dfs搜索
public class Solution { PRivate char[] str; private char[] matrix ; private boolean[][]vis ; private int[]dx = {1 , -1 , 0 , 0} ; private int[]dy = {0 , 0 , 1 , -1} ; private int rows ; private int cols ; public boolean haspath(char[] matrix, int rows, int cols, char[] str){ this.matrix = matrix ; this.str = str ; this.rows = rows ; this.cols = cols ; this.vis = new boolean[rows][cols] ; for(int i = 0;i < rows;i++){ for(int j = 0;j < cols;j++){ if(hasPath(0 , i , j)){ return true ; } } } return false ; } private boolean hasPath(int step , int x , int y){ if(str[step] != matrix[x*cols+y] || vis[x][y]) return false ; if(step == str.length-1)return true ; vis[x][y] = true ; for(int i = 0;i < 4;i++){ int nx = x + dx[i] ; int ny = y + dy[i] ; if(nx < 0 || nx >= rows || ny < 0 || ny >= cols) continue ; if(hasPath(step+1 , nx , ny)) return true ; } vis[x][y] = false ; return false ; }}
新闻热点
疑难解答