All problems

Problem 749

Word Ladder II

Hard · 30 pts · Graph, Breadth-First Search, Backtracking, String

Problem

A transformation sequence goes from BEGIN to END by changing exactly one letter at a time, and every word after BEGIN must be in the word list. Print all shortest transformation sequences. First print how many there are (0 if END cannot be reached), then each sequence on its own line, as words separated by spaces, with the sequences sorted in lexicographic order of their text. Run a breadth-first search level by level, recording for each word its parents on the previous level, then rebuild every path backwards from END.

Input

The first line contains BEGIN and END. The second line contains N. The third line contains the N words of the list. All words have the same length and use lowercase letters.

Output

Print the number of shortest sequences, then each sequence on its own line in lexicographic order.

Constraints

1 <= |word| <= 5; 1 <= N <= 500; words in the list are distinct; BEGIN != END

Example input

hit cog
6
hot dot dog lot log cog

Example output

2
hit hot dot dog cog
hit hot lot log cog

Explanation

From hit to cog with the list hot dot dog lot log cog, the shortest sequences take 4 steps: hit hot dot dog cog and hit hot lot log cog. So the answer is 2 followed by these two lines.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Number of Distinct Islands Next: Minimum Multiplications to Reach End