-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path079_Word_Search.cpp
48 lines (43 loc) · 975 Bytes
/
079_Word_Search.cpp
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
47
48
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
int dr[] = { -1,1,0,0 };
int dc[] = { 0,0,-1,1 };
class Solution {
public:
string w;
vector<vector<char>> b;
int nr, nc;
bool dfs(int r, int c, int cnt) {
if (r >= 0 && r < nr && c >= 0 && c < nc && cnt < w.size() && b[r][c] == w[cnt]) {
if (cnt == w.size() - 1) return true;
bool flag = false;
char ch = b[r][c];
b[r][c] = '#';
for (int i = 0; i != 4; i++) {
if (dfs(r + dr[i], c + dc[i], cnt + 1))
{
// cout<< r << c << endl;
flag = true; // 不能直接返回true,必须在将visited数组复位之后返回结果。
break;
}
}
b[r][c] = ch;
return flag;
}
return false;
}
bool exist(vector<vector<char>>& board, string word) {
w = word;
b = board;
nr = b.size();
nc = b[0].size();
for (int r = 0; r != nr; r++) {
for (int c = 0; c != nc; c++) {
if (dfs(r, c, 0)) return true;
}
}
return false;
}
};