劍指筆記—矩陣中的路徑

題目:請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如 a b c e s f c s a d e e 矩陣中包含一條字符串"bccced"的路徑,但是矩陣中不包含"abcb"路徑,因爲字符串的第一個字符b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。

思路:看到這種題還是一臉懵逼。。。。只想到先把整個的字符串轉化爲二維字符數組,結果這個還轉換錯了。。。沒想到要用遞歸,想到的是要用深度優先搜索,但是好像不行。

代碼:

public class Solution {
    
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {
        if(matrix==null||matrix.length==0||str==null||str.length==0)
            return false;
        if(rows==0||cols==0){
            return false;
        }
        char [][]dp=new char[rows][cols];
        boolean [][]marked=new boolean[rows][cols];
        //把整個字符串轉化爲數組的時候出錯了
        for(int i=0,index=0;i<rows;i++){
            for(int j=0;j<cols;j++){
             dp[i][j]=matrix[index++];   
            }
        }
        
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
             
                    if(method(dp,str,marked,0,i,j))
                       return  true;  
            }
        }
        return false;
    
    }
    public static boolean  method(char[][] matrix,char[]str,boolean[][]marked,int index,int i,int j){
        if(index==str.length)
            return true;
        int rows=matrix.length;
        int cols=matrix[0].length;
     if(i<0||i>=rows||j<0||j>=cols||index<0||index>=str.length||marked[i][j]||matrix[i][j]!=str[index]){
         return false;
     }
        marked[i][j]=true;
       if(method(matrix,str,marked,index+1,i-1,j)||method(matrix,str,marked,index+1,i+1,j)||method(matrix,str,marked,index+1,i,j+1)||
          method(matrix,str,marked,index+1,i,j-1)){
           return true;
           
       }
        marked[i][j]=false;
        return false;
    }


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章