題意
請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如
例如
矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因爲字符串的第一個字符b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。
思路
class Solution {
public:
bool core(char *matrix, int row, int col, int rows, int cols, char *str, bool **visit) {
//這是個遞歸調用,傳入到最後了,說明整個字符串檢測完了,返回true
if (*str == 0)
return true;
//如果當前要訪問的格子超過邊界,或者不相等,或者已經被訪問過了,都要返回false
if (row >= rows || col >= cols || row < 0 || col < 0 || matrix[col + row * cols] != *str || visit[row][col])
return false;
bool has_path = false;
//假設當前格子被訪問
visit[row][col] = 1;
//遞歸的思想,從當前格子出發,上下左右是否有路徑
has_path = core(matrix, row + 1, col, rows, cols, str + 1, visit) ||
core(matrix, row, col + 1, rows, cols, str + 1, visit) ||
core(matrix, row - 1, col, rows, cols, str + 1, visit) ||
core(matrix, row, col - 1, rows, cols, str + 1, visit);
//如果沒有路徑,就回退,然後這個格子變成沒訪問過的
if (!has_path)
visit[row][col] = 0;
//返回
return has_path;
}
bool hasPath(char *matrix, int rows, int cols, char *str) {
//設計一個visit數組,用來標記已經訪問過的單元
bool **visit = new bool *[rows];
for (int i = 0; i < rows; i++)
visit[i] = new bool[cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
visit[i][j] = 0;
//從任意單元格開始檢測是否存在指定字符串
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) {
if (core(matrix, i, j, rows, cols, str, visit))
return true;
}
return false;
}
};