-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path61-word-search.cpp
66 lines (62 loc) · 1.56 KB
/
61-word-search.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
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
bool helper(vector<vector<char>>& board, string word, int i, int j, int index)
{
if(word[index] == '\0')
{
return true;
}
if(i < 0 || j < 0 || i >= board.size() || j >= board[0].size() || board[i][j] != word[index])
{
return false;
}
else
{
char temp = board[i][j];
board[i][j] = ' ';
bool ans = helper(board, word, i + 1, j, index + 1) ||
helper(board, word, i - 1, j, index + 1) ||
helper(board, word, i, j + 1, index + 1) ||
helper(board, word, i, j - 1, index + 1);
board[i][j] = temp;
return ans;
}
}
bool isWordExist(vector<vector<char>>& board, string word) {
for(int i = 0; i < board.size(); ++i)
{
for(int j = 0; j < board[0].size(); ++j)
{
if(helper(board, word, i, j, 0))
{
return true;
}
}
}
return false;
}
};
// { Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
int n, m;
cin >> n >> m;
vector<vector<char>>board(n, vector<char>(m, '*'));
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
cin >> board[i][j];
string word;
cin >> word;
Solution obj;
bool ans = obj.isWordExist(board, word);
if(ans)
cout << "1\n";
else cout << "0\n";
}
return 0;
} // } Driver Code Ends