自己写的剑指offer步数题

bool hasOneCore(const char *matrix, int row, int col, int rows, int cols, const char *str, int &index, bool *visited) {
if(str[index] == '\0')
return true;
bool hasPath = false;
if(str[index] == matrix[col * row + col] && row >= 0 && row < rows && col >= 0 && col < cols && !visited[cols * rows + col]) {
index++;
visited[cols * row + col] = true;
hasPath = hasOneCore(matrix, row - 1, col, rows, cols, str, index, visited) ||
hasOneCore(matrix, row + 1, col, rows, cols, str, index, visited) || hasOneCore(matrix, row, col - 1, rows, cols, str, index, visited)
|| hasOneCore(matrix, row, col + 1, rows, cols, str, index, visited);
}
if(!hasPath) {
--index;
visited[row * cols + col] = false;
}
return hasPath;
};
bool hasPath(char *matrix, int rows, int cols, char *str) {
// if(matrix == nullptr || rows < 1 || cols < 1 || str == nullptr)
// return false;
int index = 0;
bool *visited = new bool[cols * rows];
memset(visited, 0, rows * cols);
for(int row = 0; row < rows; row++) {
for(int col = 0; col < cols; col++)
if(hasOneCore(matrix, row, col, rows, cols, str, index, visited)) {
return true;
}
}
delete[] visited;
return false;
};

bug太多改了很久不够系统。

posted on 2017-08-02 23:41  bloomingFlower  阅读(133)  评论(0编辑  收藏  举报