-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path123.h
60 lines (52 loc) · 2.11 KB
/
123.h
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
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
public:
/*
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
bool exist(vector<vector<char>> &board, string &word) {
// write your code here
vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));
for(int i = 0; i < board.size(); i++){
for(int j = 0; j < board[0].size(); j++){
if(board[i][j] == word[0]){
if(exist(board, word, visited, i, j, 0))
return true;
}
}
}
return false;
}
bool exist(vector<vector<char>> &board, string &word, vector<vector<bool>> &visited,
int x, int y, int start){
if(start >= word.size()){
return true;
}
if(x >= board.size() || x < 0
|| y < 0 || y >= board[0].size()
|| board[x][y] != word[start]
|| visited[x][y]){
return false;
}
// visited[x][y] = true;
// bool hor1 = false, hor2 = false, ver1 = false, ver2 = false;
// if (exist(board, word, visited, x, y-1, start+1)
// || exist(board, word, visited, x, y+1, start+1)
// || exist(board, word, visited, x-1, y, start+1)
// || exist(board, word, visited, x+1, y, start+1))
// return true;
// visited[x][y] = false; // 回溯
// return false;
// 上面这段代码会TLE, why?
visited[x][y] = true;
bool hor1 = false, hor2 = false, ver1 = false, ver2 = false;
if (exist(board, word, visited, x, y-1, start+1)
|| exist(board, word, visited, x, y+1, start+1)
|| exist(board, word, visited, x-1, y, start+1)
|| exist(board, word, visited, x+1, y, start+1))
return true;
visited[x][y] = false; // 回溯
return false;
}
};