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
44
45
46
|
class Solution {
public:
int n,m;
int slen;
bool hasPath(vector<vector<char>>& matrix, string &str) {
slen = str.size();
n = matrix.size();
if(slen == 0 || n == 0) return false;
m = matrix[0].size();
if(m == 0) return false;
for(int i=0;i<n;++i) {
for(int j=0;j<m;++j) {
if(dfs(matrix,str,i,j,0)) return true;
}
}
return false;
}
bool dfs(vector<vector<char>>& matrix, string &str,int x,int y,int len) {
if(len >= slen) return true;
char pre = matrix[x][y];
if(pre != str[len]) return false;
if(len == slen-1) return true;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
bool found = false;
matrix[x][y] = '+';
for(int i=0;i<4;++i) {
int nx = x + dx[i],
ny = y + dy[i];
if(nx>= 0 && nx <n &&ny >=0 && ny<m) {
found = found || dfs(matrix,str,nx,ny,len + 1);
if(found) break;
}
}
matrix[x][y] = pre;
return found;
}
};
|