Find the shortest walk on a 4x5 grid that starts at 0, visits museums in numeric order, and covers every non-dot cell, moving one step at a time.
Medium7BFSGraphSimulationBrute forceNo attempts yetTime limit0.5sMemory limit512 MBDetective Junha is asked to find the thief behind a run of art thefts. Several museums lost works one after another. Junha painted for a living years ago, took the news badly, and agreed to work the case at once.
The area where the thefts happened is drawn as a grid with 4 rows and 5 columns. The clues gathered so far are the cell where the thief started, the cells of the robbed museums together with the order of the thefts, and the cells where traces of the thief were found. Junha put a mathematical mind and an eye for art to work and settled on these rules for the thief.
Help Junha and find the shortest distance the thief moved.
The input holds several test cases. The first line has the number of test cases T (1≤T≤10).
Each test case is 4 lines, and each line is a string of length 5. The characters mean:
0: the cell where the thief started.A, so 10 is A and 11 is B.#: a cell where a trace of the thief was found..: a cell with no relation to the case.0 appears exactly once. The museum numbers run from 1 upward with no gaps, and no number appears twice. The grid holds 20 cells, so there are at most 19 museums and the largest label is J. A blank line separates consecutive test cases.
For each test case, print the shortest distance the thief moved, one per line. The distance is the number of times the thief stepped from one cell to another, so a thief that never moved from the starting cell gives 0.
The thief has to walk at least once on every cell that is not ., that is the starting cell, every museum cell, and every cell holding a trace. A cell already walked on can be walked on any number of times again, but museums have to be entered for the first time in the order the thefts happened.
If no route satisfies the rules, print -1.