DFS矩陣的路徑

題目描述
請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。

思路:

同“機器人的運動範圍”類似,同樣是使用DFS的路徑問題,但比上題更難的地方在於起始點不是(0,0)而是任何地方都可以,主要是要在主函數中把這個表示出來,而遞歸函數的寫法和上題套路一樣,也是邊界條件->題目滿足條件->標記->回溯

核心代碼:
主函數中循環的起始點:

   for(int i = 0; i < rows; i++)
        for(int j = 0; j < cols; j++)
        if(subHasPath(matrix,rows,cols,str,i,j,0))  //每次都是從str的起始位置開始匹配
              return true;

遞歸函數:

public boolean subHasPath(char[] matrix, int rows, int cols, char[] str, int row, int col, int len){
        if(row < 0 || col < 0 || row >= rows || col >= cols ||matrix[row*cols+col] != str[len]|| visited[row*cols+col] == true) return false;
        if(len == str.length-1) return true;
        visited[row*cols+col] = true;
        if( subHasPath(matrix,rows,cols,str,row-1,col,len+1)||
          subHasPath(matrix,rows,cols,str,row+1,col,len+1)||
          subHasPath(matrix,rows,cols,str,row,col-1,len+1)||
          subHasPath(matrix,rows,cols,str,row,col+1,len+1)) return true;
        visited[row*cols+col] = false;
        return false;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章