All problems

Problem 425

Open the Lock

Medium · 20 pts · String, Breadth-First Search, Hash Table

Problem

A lock has four wheels, each showing a digit 0-9, and starts at '0000'. In one move you turn a single wheel one step up or down, wrapping around between 9 and 0. Some combinations are dead ends: if the lock ever shows one of them, it jams and you cannot move further. Find the minimum number of moves to reach the target combination without passing through a dead end, or -1 if it is impossible (this includes the case where '0000' itself is a dead end). Breadth-first search over the 10,000 combinations finds the answer.

Input

First line: the target combination and D, the number of dead ends. Second line: the D dead-end combinations (empty if D = 0).

Output

Print the minimum number of moves, or -1.

Constraints

0 <= D <= 500; all combinations have exactly 4 digits

Example input

0202 5
0201 0101 0102 1212 2002

Example output

6

Explanation

With target 0202 and dead ends 0201 0101 0102 1212 2002, one shortest route is 0000 → 1000 → 1100 → 1200 → 1201 → 1202 → 0202, which takes 6 moves.

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

Previous: Snakes and Ladders Next: Redundant Connection