All problems

Problem 178

Word Ladder

Hard · 30 pts · Graph, Breadth-First Search, String, Hash Table

Problem

You want to turn the word BEGIN into the word END by changing exactly one letter at a time. Every word you create along the way, including END, must be in the given word list; BEGIN itself does not have to be. Print the number of words in the shortest such sequence, counting both BEGIN and END. If it cannot be done, print 0. Treat words as nodes of a graph, with an edge between words that differ in exactly one position, and run BFS from BEGIN. To find neighbours quickly, try all 26 letters at each position and check the word list with a hash set.

Input

First line: BEGIN and END. Second line: integer N. Third line: N words (all words have the same length).

Output

Print the length of the shortest transformation sequence, or 0.

Constraints

1 <= word length <= 10; 1 <= N <= 5000; lowercase letters

Example input

hit cog
6
hot dot dog lot log cog

Example output

5

Explanation

hit → hot → dot → dog → cog changes one letter at each step, and every word after hit is in the list. That sequence has 5 words, and no shorter one exists.

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

Previous: All Pairs Shortest Distance Queries Next: Max Area of Island