1. 程式人生 > >[劍指offer] 65. 矩陣中的路徑

[劍指offer] 65. 矩陣中的路徑

題目描述

請設計一個函式,用來判斷在一個矩陣中是否存在一條包含某字串所有字元的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則之後不能再次進入這個格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因為字串的第一個字元b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。
回溯法,利用一個同矩陣大小的bool陣列去儲存是否遍歷過該元素。
class Solution
{
  
public: string curStr; bool hasPath(char *matrix, int rows, int cols, char *str) { if (matrix == NULL || str == NULL || rows <= 0 || cols <= 0) return false; bool *flags = new bool[strlen(matrix)](); for (int i = 0; i < rows; i++) for
(int j = 0; j < cols; j++) if (helper(matrix, rows, cols, i, j, 0, str, flags)) return true; return false; } bool helper(char *matrix, int rows, int cols, int i, int j, int curLen, char *str, bool *flags) { int index = i * cols + j;
if (i < 0 || i >= rows || j < 0 || j >= cols || matrix[index] != str[curLen] || flags[index] == true) return false; cout << index << endl; if (curLen == strlen(str) - 1) return true; flags[index] = true; if (helper(matrix, rows, cols, i - 1, j, curLen + 1, str, flags) || helper(matrix, rows, cols, i + 1, j, curLen + 1, str, flags) || helper(matrix, rows, cols, i, j - 1, curLen + 1, str, flags) || helper(matrix, rows, cols, i, j + 1, curLen + 1, str, flags)) return true; flags[index] = false; return false; } };