您的位置:首页 > 其它

12、矩阵中的路径

2018-03-30 14:33 399 查看
public class Solution {
boolean hasPath = false;
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{   //对矩阵的每个点进行search,查到了路径就返回true
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);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: