![]() |
VOOZH | about |
You are given a list of strings, words[], and an n × m matrix of characters, letters[][]. The objective is to locate all the words from words[] that can be constructed by consecutively linking adjacent characters in the matrix. You are allowed to move in any of the 8 possible directions (horizontally, vertically, or diagonally), but each cell in the matrix can be used only once per word.
Example:
Input: words[] = [ "geeks", "for", "quiz", "go" ]
👁 Boggle
letters[][] = [[ 'g', 'i', 'z' ],
[ 'u', 'e', 'k' ],
[ 'q', 's', 'e' ]]
Output: geeks quiz
Explanation: To form the word "geeks", begin at cell (0,0) containing 'g'. Next, proceed diagonally down-right to cell (1,1) with 'e', then continue in the same diagonal direction to cell (2,2) for another 'e'. After that, move upward to cell (1,2) to pick up 'k', and finally, go diagonally down-left to cell (2,1) to complete the word with 's'.
Table of Content
The idea is to treat every cell in the matrix as a potential starting point and generate all words that begin with the cell using depth-first search. For every generated word, check if it is present in the given set of words. If yes, then add it to the result and remove it from the given words to avoid duplicates. During DFS search, it is crucial to maintain a record of visited cells, ensuring that each cell is used only once in forming any given word.
Below is given the implementation:
geeks quiz
Instead of generating all strings from the grid and then checking whether it exists in dictionary or not , we can simply run a DFS on all words present in dictionary and check whether we can make that word from grid or not.
Below is given the implementation:
quiz geeks
Related Article: