題目描述
假設矩陣爲 matrix,字符串爲 str,定義一個與矩陣等大小的 bool 矩陣 isVisited 用於標記格子是否被訪問。
1. 當在矩陣 matrix 中找到一個匹配字符串 str 的 index 處字符的格子,標記此格子爲已訪問。
2. 從該格子開始沿四個方向遞歸查找下一個格子匹配 str 的 index 處的下一個字符。
1) 若找到,則繼續遞歸匹配下一個字符,以此遞歸直到匹配到 str 的末尾,或者匹配不到了。
2) 若找不到,則回溯,重新選擇下一個和 index 處匹配的格子。
bool hasPath(char* matrix, int rows, int cols, char* str, int r, int c, int& index, bool* isVisited) {
if('\0' == str[index])// 如果到了字符串 str 的末尾, 則表示矩陣中存在一個路徑
return true;
bool isHasPath = false;
// 如果座標 <r, c> 處的格子匹配字符串 str 的 index 處的字符,則朝四個方向遞歸查找下一個匹配的字符
if(r >= 0 && r < rows && c >= 0 && c < cols &&
matrix[r*cols+c] == str[index] && !isVisited[r*cols+c]) {
index++;
isVisited[r*cols+c] = true;// 標記座標 <r, c> 處的格子爲已訪問
isHasPath = hasPath(matrix, rows, cols, str, r, c+1, index, isVisited) ||// 朝右找
hasPath(matrix, rows, cols, str, r+1, c, index, isVisited) ||// 朝下找
hasPath(matrix, rows, cols, str, r, c-1, index, isVisited) ||// 朝左找
hasPath(matrix, rows, cols, str, r-1, c, index, isVisited);// 朝上找
if(!isHasPath) {// 如果無法找到下一個匹配的格子,則回溯,重新選擇和當前字符匹配的格子
index--;
isVisited[r*cols+c] = false;
}
}
return isHasPath;
}
bool HasPath(char* matrix, int rows, int cols, char* str) {// 【矩陣中的路徑(回溯法解決)】
if(NULL == matrix || NULL == str || cols <= 0 || cols <= 0)
return false;
bool *isVisited = new bool[rows * cols]();// 用來標記格子是否被訪問過,初始化全爲 0,即 false
int index = 0;
for(int r=0; r < rows; r++)
for(int c=0; c < cols; c++)
if(hasPath(matrix, rows, cols, str, r, c, index, isVisited)) {
delete[] isVisited;
return true;
}
delete[] isVisited;
return false;
}