-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0079_Word_Search.cpp
66 lines (62 loc) · 2.05 KB
/
0079_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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Solution {
public:
bool dfs(vector<vector<char>>& board, string word, int x, int y, int k, vector<vector<bool>>& visited){
// no longer to go deeper
if(k == word.length() - 1) return true;
visited[x][y] = true;
char ch = word[k + 1];
int n = board.size();
int m = board[0].size();
if((x - 1 >= 0) && (!visited[x - 1][y]) && (board[x - 1][y] == ch)){
if(dfs(board, word, x - 1, y, k + 1, visited)) return true;
}
if((x + 1 < n) && (!visited[x + 1][y]) && (board[x + 1][y] == ch)){
if(dfs(board, word, x + 1, y, k + 1, visited)) return true;
}
if((y - 1 >= 0) && (!visited[x][y - 1]) && (board[x][y - 1] == ch)){
if(dfs(board, word, x, y - 1, k + 1, visited)) return true;
}
if((y + 1 < m) && (!visited[x][y + 1]) && (board[x][y + 1] == ch)){
if(dfs(board, word, x, y + 1, k + 1, visited)) return true;
}
visited[x][y] = false;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int n = board.size();
int k = word.length();
if((n == 0) || (k == 0)) return false;
int m = board[0].size();
vector<vector<bool>> visited;
// init flag
for(int i = 0; i < n; i++){
vector<bool> cur(m, false);
visited.push_back(cur);
}
// search by dfs
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if((board[i][j] == word[0]) && (dfs(board, word, i, j, 0, visited))){
return true;
}
}
}
return false;
}
};
int main(){
vector<vector<char> > board = {
{'A','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'}};
//string word = "ABCCED";
//string word = "SEE";
string word = "ABCB";
Solution solve;
std::cout << solve.exist(board, word) << std::endl;
return 0;
}