Given some words, e.g. banana , cat , dog, elephant, type, middle, lake
find a sequence such that
(1) every word is on the sequence
(2) any adjacent words cannot have same characters.
If the seq cannot be found, return false. otherwise, return true and the seq.
No duplicated. No permutations of words.
My idea:
Set up a graph, and use Hamiltonian path to find the seq.
But, it is a NP complete.
How to avoid Hamiltonian path ?
Any better ideas ?
thanks
Note that if you have constructed a partial sequence, it is only the last word that determines which other words you may continue the sequence with. For instance, if you have selected "banana" and "dog", you may continue with "type" or "lake" (it doesn't matter that "lake" collides with "banana", because "lake" will be adjacent to "dog"). Since you must use the words in the order they appear (if I understand your description correctly), you can use dynamic programming to solve the problem "what is the longest sequence of words I can produce that ends with the i th word?"
My approach would involve a struct:
c1 would be the first character in str, and c2 would be the last. I would loop over the input array and generate a node for each item, and probably put them into a std::vector. Then on each node, push_back() a reference to all the nodes that could be validly placed in front of that node in to valid. Then I would recursively look for the path. Just start with the first node, label it used, navigate to the first index of valid, repeat for that node, then when control returns to that point, go to the next node in valid, do the same, then when returning from here, reset the used value in all the nodes. If a match isn't found, return false.
Here's a bit of code. It makes sure that the first and last letter of each word do not match. Modify the qualifying expression to suit your needs.