矩阵中的路径

  • 使用标记数据,默认值是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;
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值