class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix char字符型vector<vector<>>
* @param word string字符串
* @return bool布尔型
*/
bool dfs(vector<vector<char> >& matrix, int i, int j, int x, string word) {
if ((i >= matrix.size()) || (i < 0) || (j >= matrix[0].size()) || (j < 0)) {
return false;
}
if (matrix[i][j] != word[x]) {
return false;
}
if (x == word.length()-1) {
return true;
}
char tmp = matrix[i][j];
matrix[i][j] = '*';
if ((dfs(matrix, i+1, j, x+1, word))
|| (dfs(matrix, i-1, j, x+1, word))
|| (dfs(matrix, i, j+1, x+1, word))
|| (dfs(matrix, i, j-1, x+1, word))) {
return true;
}
matrix[i][j] = tmp;
return false;
}
bool hasPath(vector<vector<char> >& matrix, string word) {
// write code here
int n = matrix.size();
int m = matrix[0].size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (dfs(matrix, i, j, 0, word)) {
return true;
}
}
}
return false;
}
};