1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
class Solution { public: bool hasPath(char* matrix, int rows, int cols, char* str) { if (str == nullptr || rows <= 0 || cols <= 0) return false;
vector<vector<char>> board(rows, vector<char>(cols)); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { board[i][j] = matrix[i * cols + j]; } } vector<vector<bool>> visited(rows, vector<bool>(cols, false)); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (hasPathCore(board, str, visited, i, j, 0)) return true; } } return false; }
bool hasPathCore(vector<vector<char>> &board, char* str, vector<vector<bool>> &visited, int x, int y, int index) { if (index == strlen(str)) return true; if (x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return false; if (visited[x][y]) return false; if (board[x][y] != str[index]) return false;
visited[x][y] = true; int dx[] = { -1, 0, 1, 0}, dy[] = { 0, 1, 0, -1}; for (int i = 0; i < 4; i++) { if (hasPathCore(board, str, visited, x + dx[i], y + dy[i], index + 1)) return true; } visited[x][y] = false; return false; } };
|