[65]劍指offer->矩陣中的路徑
阿新 • • 發佈:2020-11-01
題目
請設計一個函式,用來判斷在一個矩陣中是否存在一條包含某字串所有字元的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如在下面的3x4的矩陣中包含一條字串"bcced"的路徑(路徑中的字母用斜體表示)。但是矩陣中不包含"abcb"路徑,因為字串的第一個字元b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入這個格子。
思路
首先,遍歷這個矩陣,我們很容易就能找到與字串str中第一個字元相同的矩陣元素ch。
然後遍歷ch的上下左右四個字元,如果有和字串str中下一個字元相同的,就把那個字元當作下一個字元(下一次遍歷的起點),如果沒有,就需要回退到上一個字元,然後重新遍歷。為了避免路徑重疊,需要一個輔助矩陣來記錄路徑情況。
下面程式碼中,當矩陣座標為(row,col)的格子和路徑字串中下標為pathLength的字元一樣時,從4個相鄰的格子(row,col-1)、(row-1,col)、(row,col+1)以及(row+1,col)中去定位路徑字串中下標為pathLength+1的字元。
如果4個相鄰的格子都沒有匹配字串中下標為pathLength+1的字元,表明當前路徑字串中下標為pathLength的字元在矩陣中的定位不正確,我們需要回到前一個字串(pathLength-1),然後重新定位。
一直重複這個過程,直到路徑字串上所有字元都在矩陣中找到格式的位置(此時str[pathLength] == '\0')。
程式碼
class Solution { public: bool hasPath(char* matrix, int rows, int cols, char* str) { if(matrix == NULL || rows < 1 || cols < 1 || str == NULL){ return false; } bool* visited = new bool[rows*cols]; memset(visited, 0, rows*cols); int pathLength = 0; //開始遍歷尋找路徑 for(int row = 0; row < rows; row++){ for(int col = 0; col < cols; col++){ if(hasPathCore(matrix, rows, cols, row, col, str, pathLength, visited)){ delete[] visited; return true; } } } delete[] visited; return false; } private: bool hasPathCore(char* matrix, int rows, int cols, int row, int col, char* str, int& pathLength, bool* visited){ if(str[pathLength] == '\0'){ return true; } bool hasPath = false; if(row >= 0 && row < rows && col >= 0 && col < cols && matrix[row*cols+col] == str[pathLength] && !visited[row*cols+col]){ //ptah長度+1,指向下一個str ++pathLength; -------------------------------------- //將輔助矩陣當前位置標記為true | visited[row*cols+col] = true; | 1. //依次對周圍四個節點遍歷 | hasPath = \ / \/ ----------- hasPathCore(matrix, rows, cols, row-1, col, str, pathLength, visited) 3. | || hasPathCore(matrix, rows, cols, row+1, col, str, pathLength, visited) <----- | || hasPathCore(matrix, rows, cols, row, col-1, str, pathLength, visited) | | 2. || hasPathCore(matrix, rows, cols, row, col+1, str, pathLength, visited); | | | | //如果當前位置找不到路徑 | -----> if(!hasPath){ | --pathLength; --------------------------------------------------------------- visited[row*cols+col] = false; } } return hasPath; } };