-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwordSearch.cpp
57 lines (56 loc) · 1.87 KB
/
wordSearch.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
bool helper(vector<vector<char>> &board, string word, int x, int y) {
if(board[x][y]==word[0]) {
// when it's the last char in the word,
// terminate the recursion and return true;
if (word.size()==1) return true;
char c = board[x][y];
board[x][y] = '*';
if(x+1<board.size() &&board[x+1][y]!='*') {
if(helper(board, word.substr(1), x+1, y)) {
return true;
}
}
if(x-1>=0 && board[x-1][y]!='*') {
if(helper(board, word.substr(1), x-1, y)) {
return true;
}
}
if(y+1<board[0].size() &&board[x][y+1]!='*') {
if(helper(board, word.substr(1), x, y+1)) {
return true;
}
}
if(y-1>=0 && board[x][y-1]!='*') {
if(helper(board, word.substr(1), x, y-1)) {
return true;
}
}
// unmark the symbol
// backtracking
board[x][y]=c;
}
return false;
}
bool exist(vector<vector<char> > &board, string word) {
if(word=="") return true;
if(board.size()==0) return false;
if(word.size()>(board[0].size()*board.size())) return false;
vector<int> words(256, 0);
for(int i=0; i<board.size(); i++) {
for(int j=0; j<board[0].size(); j++) {
words[board[i][j]]+=1;
}
}
for(auto c:word) {
words[c]--;
if(words[c]<0) return 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(helper(board, word, i, j)) return true;
}
}
}
return false;
}