题目描述
1 class Solution { 2 public: 3 bool hasPath(char* matrix, int rows, int cols, char* str) { 4 if (matrix == nullptr || rows <= 0 || cols <= 0 || str == nullptr) { 5 return false; 6 } 7 bool *visited = new bool[rows * cols]; 8 memset(visited, false, rows * cols); 9 int pathLength = 0; 10 for (int i = 0; i < rows; i++) { 11 for (int j = 0; j < cols; j++) { 12 if (hasPathCore(matrix, rows, cols, i, j, str, visited, pathLength)) { 13 return true; 14 } 15 } 16 } 17 delete[] visited; 18 return false; 19 } 20 private: 21 bool hasPathCore(char* matrix, int rows, int cols, int i, int j, char* str, bool* visited, int pathLength) { 22 if (str[pathLength] == '\0') { 23 return true; 24 } 25 bool hasPath = false; 26 int index = i * cols + j; 27 if (i >= 0 && i < rows 28 && j >= 0 && j < cols 29 && matrix[index] == str[pathLength] 30 && !visited[index]) { 31 ++pathLength; 32 visited[index] = true; 33 hasPath = hasPathCore(matrix, rows, cols, i - 1, j, str, visited, pathLength) 34 || hasPathCore(matrix, rows, cols, i + 1, j, str, visited, pathLength) 35 || hasPathCore(matrix, rows, cols, i, j - 1, str, visited, pathLength) 36 || hasPathCore(matrix, rows, cols, i, j + 1, str, visited, pathLength); 37 if (!hasPath) { 38 --pathLength; 39 visited[index] = false; 40 } 41 } 42 return hasPath; 43 } 44 45 };