-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0079.cpp
More file actions
40 lines (32 loc) · 1.13 KB
/
Copy path0079.cpp
File metadata and controls
40 lines (32 loc) · 1.13 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
class Solution {
typedef vector<vector<char>> Matrix;
typedef vector<vector<bool>> Marked;
const vector<pair<int, int>> offsets = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int n, m;
int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
string word;
bool dfs(const Matrix &mat, Marked &mark, int a, int b, int got) {
if (got == word.size()) return true;
mark[a][b] = true;
for (auto [oa, ob] : offsets) {
int x = a + oa, y = b + ob;
if (!valid(x, y) || mark[x][y] || mat[x][y] != word[got]) continue;
if (dfs(mat, mark, x, y, got + 1)) return true;
}
mark[a][b] = false;
return false;
}
public:
bool exist(const Matrix &board, string word) {
n = board.size(), m = board[0].size();
this->word = word;
Marked visited(n, vector<bool>(m, false));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i][j] != word[0]) continue;
if (dfs(board, visited, i, j, 1)) return true;
}
}
return false;
}
};