logo CodeStepByStep logo

squishWord

Language/Type: C++ recursion backtracking set
Related Links:

Write a recursive function named squishWord that uses backtracking to try to find a way to "squish" a word down to an empty string, one letter at a time. Your function accepts two parameters: a string representing the word to try to "squish", and a reference to a set of strings representing the English dictionary.

"Squishing" a word is defined as finding a way to repeatedly remove a single letter from the word, forming another string that is a valid English word at each step, until the string is empty. If your function is able to find a valid "squish" sequence, your function should print it in the format shown below: each word in the sequence is shown in order, starting with the original word passed in, with a space between words. For example, here is a sequence of removals that can squish the word "startling":

startling starting staring string sting sing sin in i

Note that you cannot just remove any letter; if you removed the "a" in the first step, you'd get "strtling", which is not a valid English word. Each word along the way must be an English word from the dictionary for the sequence to be valid.

If there are multiple ways to "squish" the word, you should find and print only one of them. After printing one path, your code should stop without printing any other potential paths. If the string passed to your function is not a single valid English word, or if it is not possible to produce to "squish" the given string, your function should print:

No sequence found.

Assume that the dictionary has already been read from a file and contains all legal English words. You do not need to worry about any case sensitivity issues for this problem; all words will be in lowercase.

Constraints: Do not declare any global variables. You can use any data structures you like, and your code can contain loops, but the overall algorithm must be recursive and must use backtracking. You are allowed to define other "helper" functions if you like; they are subject to these same constraints. Do not modify the state of the set passed in.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.