-
Notifications
You must be signed in to change notification settings - Fork 0
/
0079_Word_Search.cpp
42 lines (42 loc) · 1.37 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
#pragma GCC optimize("Ofast","inline","ffast-math","unroll-loops","no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native","f16c")
auto init = []()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 'c';
}();
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size(), n = board[0].size();
int dirs[5] = {-1, 0, 1, 0, -1};
function<bool(int, int, int)> dfs = [&](int i, int j, int k) -> bool {
if (k == word.size() - 1) {
return board[i][j] == word[k];
}
if (board[i][j] != word[k]) {
return false;
}
char c = board[i][j];
board[i][j] = '0';
for (int u = 0; u < 4; ++u) {
int x = i + dirs[u], y = j + dirs[u + 1];
if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '0' && dfs(x, y, k + 1)) {
return true;
}
}
board[i][j] = c;
return false;
};
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (dfs(i, j, 0)) {
return true;
}
}
}
return false;
}
};