劍指offer____矩陣中的路徑
阿新 • • 發佈:2018-11-17
請設計一個函式,用來判斷在一個矩陣中是否存在一條包含某字串所有字元的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則之後不能再次進入這個格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因為字串的第一個字元b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。
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)) return true; } } delete[] visited; return false; } /*此函式用來判斷在當前路徑滿足條件下,相鄰格子中是否存在一個格子滿足條件*/ 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]) { ++pathLength; visited[row*cols + col] = true; /*如果矩陣格子(row,col)與路徑字串中下標為pathLength的字元一樣時, 從它的4個相鄰格子中尋找與路徑字串下標為pathLength+1的字元相等的格子*/ hasPath = hasPathCore(matrix, rows, cols, row, col - 1, str, pathLength, visited) || hasPathCore(matrix, rows, cols, row - 1, col, str, pathLength, visited) || hasPathCore(matrix, rows, cols, row, col + 1, str, pathLength, visited) || hasPathCore(matrix, rows, cols, row + 1, col, str, pathLength, visited); if (!hasPath) { --pathLength; //如果沒找到,則說明當前第pathLength個字元定位不正確,返回上一個位置重新定位 visited[row*cols + col] = false; } } return hasPath; } };