题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 \begin{bmatrix} a & b & c &e \\ s & f & c & s \\ a & d & e& e\\ \end{bmatrix}\quad⎣⎡asabfdcceese⎦⎤ 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
题目链接:
分析:
DFS或BFS。
public class Solution { public boolean hasPath(char[] matrix, int rows, int cols, char[] str) { int len = matrix.length; //以所有点为起点判断路径是否存在 for(int i =0;i<rows;i++){ for(int j=0;j<cols;j++){ boolean[] flag = new boolean[len]; if(DFS(matrix,rows,cols,str,i,j,0,flag)){ return true; } } } return false; } public boolean DFS(char[] matrix, int rows, int cols, char[] str,int x,int y,int pos,boolean[] flag){ //不能出遍历范围,不能走已走过的点 if(x<0||x>=rows||y<0||y>=cols||flag[x*cols+y]){ return false; } if(matrix[x*cols+y] == str[pos]){ //说明此时已全部匹配完字符串,返回true if(pos == str.length - 1){ return true; } //将当前节点访问位置设置true,表示已走过一次 flag[x*cols+y] = true; //往四个方向遍历找相应路径 return DFS(matrix,rows,cols,str,x+1,y,pos+1,flag) || DFS(matrix,rows,cols,str,x-1,y,pos+1,flag) || DFS(matrix,rows,cols,str,x,y+1,pos+1,flag) || DFS(matrix,rows,cols,str,x,y-1,pos+1,flag); } return false; } }