題目描述
請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如
矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因爲字符串的第一個字符b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。
思路
這種題一看就是用動態規劃or 遞歸
首先設置一個標籤組 false表示沒走過,true表示走過該位置
然後以矩陣的每一個節點爲初始位置,進行路徑查找。
此處用遞歸方式,提起遞歸必然有入口出口
出口:
1》當走到標籤位是true時,當行r列c索引範圍超過0~rows, o-cols時,當matrix[idx] != str[k]時;皆是f返回alse;
2》當str字符組被找完,即str[k+1]==\0時;返回true
3》否則進行上下左右遍歷
代碼
class Solution {
public:
bool hasPath(const char* matrix, int rows, int cols, const char* str) {
if (matrix == NULL || str == NULL || rows < 1 || cols < 1)
return false;
m = rows, n = cols;
//vector<bool>tag(rows * cols+1, false);
bool* tag = new bool[rows * cols];//標籤
memset(tag, false, rows * cols);
//以矩陣每一個位置爲初始點進行路徑查找
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (strpath(matrix, i, j,str, tag,0))
return true;
}
}
delete[]tag;
return false;
}
bool strpath(const char* matrix, int r, int c, const char* str, bool* tag,int k) {
int idx = r * n + c;//一維數組表示二維數組,例如a是一個三行四列素組,a[2][3]=b,那麼 代表a[2*4+3]=b
//1》當走到標籤位是true時,當行r列c索引範圍超過0~rows, o-cols時,當matrix[idx] != str[k]時;皆是f返回alse;
if(r>=m||c>=n||tag[idx]==true||r<0||c<0||matrix[idx] != str[k])
return false;
//2》當str字符組被找完,即str[k+1]==\0時;返回true
if (str[k+1] == '\0')
return true;
//3》否則進行上下左右遍歷尋找
tag[idx] = true;//將要走這個位置直接設置爲true
if (strpath(matrix, r-1, c, str, tag,k+1) || strpath(matrix, r, c-1, str, tag, k + 1) || strpath(matrix, r+1, c, str, tag, k + 1) || strpath(matrix, r, c+1, str, tag, k + 1)) {
return true;
}
tag[idx] = false;//能走到這一步說明此路不通,要恢復這個位置的索引爲false。
return false;
}
private:
int m=0, n=0;//m和n 分別記住矩陣行列最大值。
};