本文首發于我的個人部落格: 尾尾部落
題目描述
請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字元串所有字元的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則之後不能再次進入這個格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字元串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因為字元串的第一個字元b占據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。
解題思路
回溯法:
- 将matrix字元串映射為一個字元矩陣(
)index = i * cols + j
- 周遊matrix的每個坐标,與str的首個字元對比,如果相同,用flag做标記,matrix的坐标分别上、下、左、右、移動(判斷是否出界或者之前已經走過[flag的坐标為1]),再和str的下一個坐标相比,直到str全部對比完,即找到路徑,否則找不到。
參考代碼
public class Solution {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
if(matrix.length == 0 || str.length == 0)
return false;
int [][] flag = new int[rows][cols];
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(search(matrix, rows, cols, i, j, str, 0, flag))
return true;
}
}
return false;
}
public boolean search(char[] matrix, int rows, int cols,
int i, int j, char[] str, int index, int[][] flag){
int m_i = i * cols + j;
if(i<0 || j<0 || i >= rows || j>=cols || flag[i][j] == 1 || matrix[m_i] != str[index])
return false;
if(index >= str.length - 1)
return true;
flag[i][j] = 1;
if(search(matrix, rows, cols, i+1, j, str, index+1, flag) ||
search(matrix, rows, cols, i-1, j, str, index+1, flag) ||
search(matrix, rows, cols, i, j+1, str, index+1, flag) ||
search(matrix, rows, cols, i, j-1, str, index+1, flag))
return true;
flag[i][j] = 0;
return false;
}
}