Given a 2D matrix of characters and a target word, write a function that returns whether the word can be found in the matrix by going left-to-right, or up-to-down.
For example, given the following matrix:
[['F', 'A', 'C', 'I'],
['O', 'B', 'Q', 'P'],
['A', 'N', 'O', 'B'],
['M', 'A', 'S', 'S']]
and the target word 'FOAM', you should return true, since it's the leftmost column. Similarly, given the target word 'MASS', you should return true, since it's the last row.
Example:
Input: board={{'F','A','C',I'},{'O','B','Q','P'},{'A','N','O','B'},{'M','A','S','S'}}, word="FOAM"
Output: true
Approach
C++
#include <bits/stdc++.h>using namespace std;//structure for triestruct Trie{bool isleaf;unordered_map<char, Trie *> ump;Trie(){isleaf = false;}};//create a new nodeTrie *newNode(){Trie *node = new Trie();return node;}//function to insert the word into the trievoid insert(Trie *head, string word){//if head is null then//create a new nodeif (head == NULL)head = newNode();Trie *curr = head;//iterate till the length of wordfor (int i = 0; i < word.size(); i++){//if current element of word is not//present the create a new node for itif (curr->ump.find(word[i]) == curr->ump.end())curr->ump[word[i]] = newNode();//update the current to the new character//of the stringcurr = curr->ump[word[i]];}//mark the isleaf as truecurr->isleaf = true;}bool dfs(Trie *curr, vector<vector<char>> &board, int i, int j){//base case if current leaf is true//then return true as the word is found in the gridif (curr->isleaf)return true;//check for valid cell or notif (i < 0 || j < 0 || i >= board.size() ||j >= board[0].size() || (curr->ump.find(board[i][j])== curr->ump.end()))return false;//store the current cell datachar ch = board[i][j];//mark is as visitedboard[i][j] = '.';//call dfs for up to down or left to rightif (dfs(curr->ump[ch], board, i + 1, j) ||dfs(curr->ump[ch], board, i, j + 1))return true;//reset the current data as the previous//as same as backtrackboard[i][j] = ch;//if word is not found then return falsereturn false;}//function to check if word is found in the grid or//notbool exist(vector<vector<char>> &board, string word){//create a new trieTrie *node = new Trie();//insert the word into the trieinsert(node, word);Trie *temp = node;//iterate for all cellsfor (int i = 0; i < board.size(); i++){for (int j = 0; j < board[0].size(); j++)if (temp->ump[board[i][j]] && dfs(node, board, i, j))return true;}return false;}int main(){vector<vector<char>> board = {{'F', 'A', 'C', 'I'},{'O', 'B', 'Q', 'P'},{'A', 'N', 'O', 'B'},{'M', 'A', 'S', 'S'}};string word = "FOAM";if (exist(board, word))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment