From 5b9099d42ba40f36a5986a31598d123d3bf4805f Mon Sep 17 00:00:00 2001 From: tanishagarg1803 Date: Tue, 5 Oct 2021 14:32:56 +0530 Subject: [PATCH] added new recursion question --- 03. Recursion/FindTheStringInGrid.cpp | 81 +++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 03. Recursion/FindTheStringInGrid.cpp diff --git a/03. Recursion/FindTheStringInGrid.cpp b/03. Recursion/FindTheStringInGrid.cpp new file mode 100644 index 00000000..c5b463cd --- /dev/null +++ b/03. Recursion/FindTheStringInGrid.cpp @@ -0,0 +1,81 @@ +#include +using namespace std; + +// } Driver Code Ends +class Solution +{ +public: + vector> searchWord(vector> grid, string word) + { + vector> ans; + int n = grid.size(); + int m = grid[0].size(); + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + if (grid[i][j] == word[0] && isword(i, j, word, grid)) + { + ans.push_back({i, j}); + } + } + } + return ans; + // Code here + } + bool isword(int i, int j, string word, vector> grid) + { + vector> dirs = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}}; + int n = grid.size(); + int m = grid[0].size(); + for (auto dir : dirs) + { + int mini = i, minj = j; + int c = 0; + while (mini >= 0 && minj >= 0 && mini < n && minj < m && c < word.length() && grid[mini][minj] == word[c]) + { + mini = mini + dir[0]; + minj = minj + dir[1]; + c++; + } + if (c == word.length()) + { + return true; + } + } + return false; + } +}; + +// { Driver Code Starts. +int main() +{ + int tc; + cin >> tc; + while (tc--) + { + int n, m; + cin >> n >> m; + vector> grid(n, vector(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> ans = obj.searchWord(grid, word); + for (auto i : ans) + { + for (auto j : i) + cout << j << " "; + cout << "\n"; + } + if (ans.size() == 0) + { + cout << "-1\n"; + } + } + return 0; +} // } Driver Code Ends \ No newline at end of file