-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPOTD-Find the string in grid.cpp
80 lines (75 loc) · 1.78 KB
/
POTD-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
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
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
vector<vector<int>>searchWord(vector<vector<char>>grid, string word){
// Code here
vector<int> dx={-1,-1,-1,0,1,1,1,0};
vector<int> dy={-1,0,1,1,1,0,-1,-1};
int n=grid.size();
int m=grid[0].size();
vector<vector<int>>s;
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};
s.push_back(t);
break;
}
}
}
}
sort(s.begin(),s.end());
return s;
}
};
//{ Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
int n, m;
cin >> n >> m;
vector<vector<char>>grid(n, vector<char>(m,'x'));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++)
cin >> grid[i][j];
}
string word;
cin >> word;
Solution obj;
vector<vector<int>>ans = obj.searchWord(grid, word);
if(ans.size() == 0)
{
cout<<"-1\n";
}
else
{
for(auto i: ans){
for(auto j: i)
cout << j << " ";
cout << "\n";
}
}
}
return 0;
}
// } Driver Code Ends