题解 | #矩阵中的路径#
矩阵中的路径
http://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6
典型的DFS,深度优先搜索
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix char字符型vector<vector<>>
* @param word string字符串
* @return bool布尔型
*/
int n,m,l;
bool ans = false;
string w;//定义一些类内全局变量
bool hasPath(vector<vector<char> >& matrix, string word) {
// write code here
m = matrix.size();
if(m == 0)return false;
n = matrix[0].size();
if(n == 0)return false;
l = word.size();
vector<vector<bool>> visit(m, vector<bool>(n, false));
w = word;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(ans)return ans;
if(matrix[i][j] == word[0]){
dfs(matrix, visit, i, j, 0);
}
}
}
return ans;
}
void dfs(vector<vector<char>> &matrix, vector<vector<bool>> visit, int i, int j, int k){
if(0<=i && i < m && 0<=j && j<n && visit[i][j] == false){
if(matrix[i][j] == w[k]){
visit[i][j] = true;
if(k == l-1){
ans = true;
return;
}
dfs(matrix, visit, i-1, j, k+1);
dfs(matrix, visit, i+1, j, k+1);
dfs(matrix, visit, i, j-1, k+1);
dfs(matrix, visit, i, j+1, k+1);
}
}
}
};