-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path79.cpp
81 lines (71 loc) · 1.83 KB
/
79.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <set>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool dfs(int i, int j, int index, vector<vector<char>>& board, string& word,
set<pair<int, int>>& visited) {
const int rows = board.size();
const int cols = board[0].size();
if (i < 0 || i >= rows || j < 0 || j >= cols) {
return false;
}
if (visited.find(make_pair(i, j)) != visited.end()) {
return false;
}
if (index == word.length()) {
return true;
}
if (board[i][j] != word[index]) {
return false;
} else if (index + 1 == word.length()) {
return true;
}
visited.insert(make_pair(i, j));
if (dfs(i - 1, j, index + 1, board, word, visited)) {
return true;
} else {
visited.clear();
visited.insert(make_pair(i, j));
}
if (dfs(i + 1, j, index + 1, board, word, visited)) {
return true;
} else {
visited.clear();
visited.insert(make_pair(i, j));
}
if (dfs(i, j - 1, index + 1, board, word, visited)) {
return true;
} else {
visited.clear();
visited.insert(make_pair(i, j));
}
if (dfs(i, j + 1, index + 1, board, word, visited)) {
return true;
} else {
visited.clear();
visited.insert(make_pair(i, j));
}
visited.clear();
return false;
}
bool exist(vector<vector<char>>& board, string word) {
const int rows = board.size();
const int cols = board[0].size();
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) {
set<pair<int, int>> visited;
if (dfs(i, j, 0, board, word, visited)) {
return true;
}
}
return false;
}
};
int main(int argc, char const* argv[]) {
Solution s;
vector<vector<char>> grid = {{'a', 'b'}, {'c', 'd'}};
s.exist(grid, "cdba");
return 0;
}