forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0079-word-search.cpp
51 lines (42 loc) · 1.38 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
/*
Given a char board & a word, return true if word exists in the grid
DFS traversal, set visited cells to '#', search in 4 directions, backtrack
Time: O(n x 3^l) -> n = # of cells, l = length of word
Space: O(l)
*/
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
int n = board[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == word[0]) {
if (dfs(board, word, 0, i, j, m, n)) {
return true;
}
}
}
}
return false;
}
private:
bool dfs(vector<vector<char>>& board, string word,
int index, int i, int j, int m, int n) {
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[index]) {
return false;
}
if (index == word.size() - 1) {
return true;
}
board[i][j] = '#';
if (dfs(board, word, index + 1, i - 1, j, m, n)
|| dfs(board, word, index + 1, i + 1, j, m, n)
|| dfs(board, word, index + 1, i, j - 1, m, n)
|| dfs(board, word, index + 1, i, j + 1, m, n)) {
return true;
}
board[i][j] = word[index];
return false;
}
};