-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathword_search.cpp
31 lines (29 loc) · 1.13 KB
/
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
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (word.empty()) return true;
if (board.empty() || board[0].empty()) return false;
m = board.size();
n = board[0].size();
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
// traverse the board to find the first char
if (dfsSearch(board, word, 0, i, j)) return true;
return false;
}
private:
int m;
int n;
bool dfsSearch(vector<vector<char>>& board, string& word, int k, int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n || word[k] != board[i][j]) return false;
if (k == word.length() - 1) return true; // found the last char
char cur = board[i][j];
board[i][j] = '*'; // used
bool search_next = dfsSearch(board, word, k+1, i-1 ,j)
|| dfsSearch(board, word, k+1, i+1, j)
|| dfsSearch(board, word, k+1, i, j-1)
|| dfsSearch(board, word, k+1, i, j+1);
board[i][j] = cur; // reset
return search_next;
}
};