-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0079.cpp
More file actions
38 lines (30 loc) · 909 Bytes
/
0079.cpp
File metadata and controls
38 lines (30 loc) · 909 Bytes
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
class Solution {
public:
bool dfs(vector<vector<char>> &board, string &word, int i, int j, int idx) {
if (idx == word.size())
return true;
int n = board.size();
int m = board[0].size();
if (i < 0 || i >= n || j < 0 || j >= m || board[i][j] != word[idx])
return false;
char part = board[i][j];
board[i][j] = '#';
bool found = dfs(board, word, i + 1, j, idx + 1) ||
dfs(board, word, i - 1, j, idx + 1) ||
dfs(board, word, i, j + 1, idx + 1) ||
dfs(board, word, i, j - 1, idx + 1);
board[i][j] = part;
return found;
}
bool exist(vector<vector<char>> &board, string word) {
int n = board.size();
int m = board[0].size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (dfs(board, word, i, j, 0))
return true;
}
}
return false;
}
};