# 剑指offer——矩阵中的路径

xiaoxiao2021-03-01  2

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 flag[rows * cols]; memset(flag, 0, sizeof(flag)); int k = 0; for(int row = 0; row < rows; row++){ for(int col = 0; col < cols; col++){ if(start(matrix, rows, cols, str, row, col, k, flag)) return true; } } return false; } bool start(char* matrix, int rows, int cols, char* str, int row, int col, int &k, bool *flag){//row col从0开始 if(str[k] == '\0') return true; int index = row * cols + col; bool isOK = false; if(row > -1 && row < rows && col > -1 && col < cols && flag[index] == false && matrix[index] == str[k]){ flag[index] = true; k++; isOK = start(matrix, rows, cols, str, row + 1, col, k, flag) || start(matrix, rows, cols, str, row - 1, col, k, flag) || start(matrix, rows, cols, str, row, col + 1, k, flag) || start(matrix, rows, cols, str, row, col - 1, k, flag); if(!isOK){//此判断需放在上一个if内 k--; flag[index] = false; } } return isOK; } };