-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day 185: Find the string in grid.cpp
45 lines (35 loc) · 1.33 KB
/
Day 185: Find the string in grid.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
class Solution {
public:
vector<vector<int>>searchWord(vector<vector<char>>grid, string word){
int dx[] = { -1 , 1 , 0 , 0 , -1 , -1 , 1 , 1 };
int dy[] = { 0 , 0 , -1 , 1 , -1 , 1 , -1 , 1 };
int n = grid.size();
int m = grid[0].size();
vector<vector<int>> ans;
auto valid = [&](int x, int y, int p) -> bool {
if(x < 0 or x >= n or y < 0 or y >= m)
return 0;
return grid[x][y] == word[p];
};
function<bool(int, int, int, int)> helper = [&](int x, int y, int dir, int p) -> bool {
if(p == word.size() - 1)
return 1;
if(valid(x + dx[dir], y + dy[dir], p + 1))
return helper(x + dx[dir], y + dy[dir], dir, p + 1);
return 0;
};
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
for(int k = 0; k < 8; k++){
if(valid(i, j, 0) and helper(i, j, k, 0)){
vector<int> t = {i, j};
ans.push_back(t);
break;
}
}
}
}
sort(ans.begin(), ans.end());
return ans;
}
};