Holedox Moving
Time limit1sMemory limit128 MB
Find the minimum number of moves for a snake of length up to 8 to slide its head to the exit at (1,1) on a grid with stones, where the tail cell counts as blocked during a move.
- Level
Hard8 of 10
- Topics
- BFS, Simulation, Bit manipulation, Implementation
- Solved
- No attempts yet
Problem
Holedox is a small snake that lives in a maze. The maze is a grid of cells; each cell is either a stone or an empty cell, and Holedox may only travel through empty cells. Cells are addressed by (row, column), and the maze exit is the cell (1, 1).
Holedox's body has length and is described block by block as , where is adjacent to for every . is the head and is the tail.
To make one move, Holedox chooses a cell adjacent to its head that is empty — that is, the cell is not a stone and is not currently occupied by any block of its body, the tail included. It moves the head into that cell, and at the same time every other block slides into the cell that the block ahead of it just left: into the old cell of , into the old cell of , and so on up to .
For example, suppose the body is . If the only cell the head can move into is , then after one move the body becomes .
Given the maze and the starting position of every block of Holedox's body, compute the minimum number of moves the head needs to reach the exit (1, 1).

Input
The input contains several test cases.
Each test case begins with a line of three integers , () and (): the number of rows, the number of columns, and the length of Holedox's body. The next lines each contain a row and a column, giving the starting positions of through in order, with and . The next line contains an integer , the number of stones, and the following lines each contain the row and column of one stone.
Consecutive test cases are separated by a blank line. The input ends with a line containing three zeros.
It is guaranteed that is adjacent to for , and that the exit cell (1, 1) is never a stone.
Output
For each test case, print a single line Case X: S, where is the test-case number (starting from 1) and is the minimum number of moves the head needs to reach the exit. Print -1 for if the head can never reach the exit.
Hint
In the first example one optimal route for the head is , which takes 9 moves. Note that the head cannot begin by stepping to : even though the tail is about to leave that cell, it is still occupied at the moment of the move.