Untitled
unknown
plain_text
16 days ago
2.6 kB
3
Indexable
Never
#include<iostream> #include<string> #include<vector> using namespace std; /* * grid, represents the letters in the grid of size N*M. * word, represents the words to be searched of size K. */ void funcPuzzle (vector<vector<char>> &grid, const vector<string> &word) { int rows = grid.size(); int cols = grid[0].size(); // Function to check if a word is found in the grid row/column forward or backward auto checkWordInGrid = [&](int start_i, int start_j, int di, int dj, const string& w) -> bool { int n = w.size(); for (int k = 0; k < n; ++k) { int ni = start_i + k * di; // next row int nj = start_j + k * dj; // next column if (ni < 0 || ni >= rows || nj < 0 || nj >= cols || grid[ni][nj] != w[k]) { return false; } } return true; }; for (const string& w : word) { bool found = false; int w_len = w.length(); // Check each row for (int i = 0; i < rows && !found; ++i) { for (int j = 0; j <= cols - w_len && !found; ++j) { // Forward row search if (checkWordInGrid(i, j, 0, 1, w)) { found = true; break; } // Backward row search if (checkWordInGrid(i, j + w_len - 1, 0, -1, w)) { found = true; break; } } } // Check each column for (int j = 0; j < cols && !found; ++j) { for (int i = 0; i <= rows - w_len && !found; ++i) { // Forward column search if (checkWordInGrid(i, j, 1, 0, w)) { found = true; break; } // Backward column search if (checkWordInGrid(i + w_len - 1, j, -1, 0, w)) { found = true; break; } } } if (found) { cout << "Yes "; } else { cout << "No "; } } cout << endl; } int main() { //input for grid int grid_row, grid_col; cin >> grid_row >> grid_col; vector<vector<char>> grid(grid_row, vector<char>(grid_col)); for (int i = 0; i < grid_row; ++i) { for (int j = 0; j < grid_col; ++j) { cin >> grid[i][j]; } } // Input for word list int word_size; cin >> word_size; vector<string> word(word_size); for (int i = 0; i < word_size; ++i) { cin >> word[i]; } funcPuzzle(grid, word); return 0; }
Leave a Comment