Skip to content

Commit d10e9ad

Browse files
author
Pranjal
authored
Merge pull request royalpranjal#21 from me-ydv-5/patch-1
Epic Systems, Amazon
2 parents fc255b5 + 327d448 commit d10e9ad

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Graphs/WordSearchBoard.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
vector<int> x({0, 1, -1, 0});
2+
vector<int> y({1, 0, 0, -1});
3+
4+
// Check if the coordinates are safe to visit
5+
bool isSafe(int a, int b, int c, int d){
6+
if(a >= 0 && a < c && b >= 0 && b < d)return true;
7+
return false;
8+
}
9+
10+
11+
void explore(bool& pivot, int val, int a, int b, vector<string>& A, string B){
12+
// If reached on the last index of the string,
13+
// it means we have found the reqd. string and
14+
// so we return
15+
if(val == B.size()-1){
16+
pivot = true;
17+
return;
18+
}
19+
20+
for(int i = 0; i < x.size(); i++){
21+
int first = a + x[i];
22+
int second = b + y[i];
23+
24+
// Explore the adjacent node only if its value is the next index in the
25+
// given string
26+
if(isSafe(first, second, A.size(), A[0].size()) && A[first][second] == B[val+1]){
27+
explore(pivot, val+1, first, second, A, B);
28+
// To reduce time limit.
29+
if(pivot == true)return;
30+
}
31+
}
32+
33+
}
34+
35+
int Solution::exist(vector<string> &A, string B) {
36+
int l = A.size(), m = A[0].size();
37+
if(l == 0)return 0;
38+
39+
bool pivot = false;
40+
for(int i = 0; i < l; i++){
41+
for(int k = 0; k < m; k++){
42+
if(A[i][k] == B[0]){
43+
explore(pivot, 0, i, k, A, B);
44+
}
45+
if(pivot)return pivot;
46+
}
47+
}
48+
return pivot;
49+
}

0 commit comments

Comments
 (0)