classSolution { public: booldfs(vector<vector<char>>& matrix, string &str, int u, int x, int y){ //视频中的错误写法(测试用例不全导致) //if (u == str.length()) return true; //if (matrix[sx][y] != str[u]) return false;
//肯定不合适 if (matrix[x][y] != str[u]) returnfalse; //已经到底了,返回ok if (u == str.length() - 1) returntrue;
int t = matrix[x][y]; matrix[x][y] = '#';
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
for (int i = 0; i < 4; ++i) { int a = x + dx[i], b = y + dy[i]; if (a >= 0 && a < matrix.size() && b >= 0 && b < matrix[a].size()) { if (dfs(matrix, str, u + 1, a, b)) returntrue; } }
matrix[x][y] = t; returnfalse; }
boolhasPath(vector<vector<char>>& matrix, string &str){ for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[i].size(); ++j) { if (dfs(matrix, str, 0, i, j)) { returntrue; } } }