Boggle
Build a game known as Boggle, find the words of a dictionary from a grid of characters in this game.
Statement
Given an grid of characters and a dictionary, find all the words that can be made from the characters in the grid and are present in the given dictionary.
-
A word can start and end at any character in the grid.
-
The next character must be adjacent to the previous character in any direction: up, down, left, right, or along any diagonal.
-
We can use the character at each position in the grid only once while making a word.
Example
Suppose we have a grid and a dictionary as input. We can make six words from the grid that are present in the dictionary. The green highlighted characters indicate that they form the word in the grid, which is also present in the dictionary.
In the grid, we start at character , then move up and left (along a diagonal) for , and then right to to make .
Sample input
grid = [['c', 'a', 't'],
['r', 'r', 'e'],
['t', 'o', 'n']]
dictionary = {"cat", "cater", "cartoon", "toon", "moon", "not", "tone", "apple", "ton", "art"}
Expected output
output = ["art", "tone", "cat", "cater", "not", "ton"]
Try it yourself
#include <string>#include <list>#include <iostream>#include <vector>#include <unordered_set>using namespace std;class Boggle {public:// Code assumes that both dimensions of the grid are the samevector<vector<char>> grid;unordered_set<string> dictionary;vector<vector<bool>> state;Boggle(const vector<vector<char>>& g, const unordered_set<string>& d): grid(g), dictionary(d) {// TODO: Write - Your - Code}// Challenge functionunordered_set<string> FindAllWords() {// TODO: Write - Your - Codeunordered_set<string> words;return words;}};
Solution
This is a backtracking problem. We start with one character in the grid and try to make as many words as possible starting with that character. We repeat the same process for all characters in the grid.
To find all the words starting with a character, we use an algorithm very similar to depth-first search. As every ...