public class Solution {
boolean hasPath = false;
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
boolean[] visited = new boolean[rows*cols];
search(matrix,rows,cols,i,j,0,str,visited);
if(hasPath == true)
return true;
}
}
return false;
}
public void search(char[] matrix,int rows, int cols,int row,int col,int k,char[] str,boolean[] visited)
{
if((row>-1) && (row<rows) && (col>-1) && (col<cols) && (visited[row*cols+col]==false))
{
if(matrix[cols*row+col]==str[k])
{
if(k==str.length-1)
{
hasPath=true;
return;
}
visited[cols*row+col] = true;
search(matrix,rows,cols,row,col-1,k+1,str,visited);
search(matrix,rows,cols,row,col+1,k+1,str,visited);
search(matrix,rows,cols,row-1,col,k+1,str,visited);
search(matrix,rows,cols,row+1,col,k+1,str,visited);
}
}
}
}