- 使用标记数据,默认值是false,走过的标记为true,走完返回上一层时候标记为false
- 有两种情况返回,出界,或走到标记为ture的地方
- 判断结果是否正确,通过最后一次递归,统计长度是否达到指定的值
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix char字符型二维数组
* @param word string字符串
* @return bool布尔型
*/
public boolean hasPath (char[][] matrix, String word) {
// write code here
if(matrix==null)
{
return false;
}
int row=matrix.length;
int col=matrix[0].length;
//默认是false
boolean[][] route=new boolean[row][col];
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
{
if(visited(matrix, word,i,j,0,route))
{
return true;
}
}
return false;
}
boolean visited(char[][] matrix, String word,int rows,int cols,int count,boolean[][] route)
{
if(count==word.length())
{
return true;
}
int row=matrix.length;
int col=matrix[0].length;
//不出界
if(rows<0||rows==row||cols<0||cols==col)
{
return false;
}
//不重复走
if(route[rows][cols]==true)
{
return false;
}
if(matrix[rows][cols]==word.charAt(count))
{
//标记为走过
route[rows][cols]=true;
//四个方向,如果最早的那一层递归判断错误,不执行return true执行return false;
if(visited(matrix, word,rows+1,cols,count+1,route)||visited(matrix, word,rows,cols+1,count+1,route)||visited(matrix, word,rows-1,cols,count+1,route)||visited(matrix, word,rows,cols-1,count+1,route))
{
return true;
}
route[rows][cols]=false;
}
return false;
}
}