-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord_Search.cpp
More file actions
58 lines (46 loc) · 1.42 KB
/
Copy pathWord_Search.cpp
File metadata and controls
58 lines (46 loc) · 1.42 KB
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
#include <vector>
#include <string>
class Solution {
public:
bool exist(std::vector<std::vector<char>>& board, std::string word) {
for (int row=0; row<board.size(); row++) {
for (int col=0; col<board[0].size(); col++) {
if (helper(board, word, row, col, 0)) {
return true;
}
}
}
return false;
}
bool helper(std::vector<std::vector<char>>& board, std::string word, int row, int col, int index) {
// word found
if (index == word.size()) {
return true;
}
if (row >= board.size() || row < 0 || col >= board[0].size() || col < 0) {
return false;
}
if (board[row][col] == '-1') {
return false;
}
if (board[row][col] != word[index]) {
return false;
}
board[row][col] = '-1'; // mark the current cell as visited
// Traverse the four directions
if (helper(board, word, row-1, col, index+1)) {
return true;
}
if (helper(board, word, row+1,col, index+1)) {
return true;
}
if (helper(board, word, row, col-1, index+1)) {
return true;
}
if (helper(board, word, row,col+1, index+1)) {
return true;
}
board[row][col] = word[index]; // re-mark cell as non-visited
return false;
}
};