LogiQuest

292. Word Ladder

HardBFS

Transform the begin word into the end word changing one letter at a time; every intermediate word must be in the dictionary. Print the number of words in the shortest transformation sequence (including begin and end), or 0.

Input format

Line 1: begin end Line 2: k Line 3: k dictionary words

Output format

The sequence length, or 0.

Example 1

Input

hit cog
6
hot dot dog lot log cog

Output

5

Example 2

Input

hit cog
5
hot dot dog lot log

Output

0

Constraints

1 ≤ k ≤ 5000 All words have the same length (≤ 10).

Read input from standard input and print the answer to standard output. Your code is judged against 3 test cases, most of them hidden.

Loading the MyLoginn IDE…