Car Vet
Time limit2sMemory limit512 MB
Given a grid of cars and one empty cell, find the fewest car moves that uncover a given cell, breaking ties by lowest car number, or report impossible.
- Level
Medium7 of 10
- Topics
- Graph, BFS, Shortest path
- Solved
- No attempts yet
Problem
Bob Roberts is a self-proclaimed Car Vet who owns several junk car lots where people can come and search for spare parts for their (ailing) cars. The cars in each lot are parked in a fenced-in grid, and each car takes up two grid squares. Each lot also has zero or more grid locations holding piles of parts (fenders, 8-track tape players, wheel covers, fuzzy dice, etc.). These locations are blocked. Business is so good that each lot has only one empty grid square left.

Now and then, Bob or one of his attendants drops a part on the ground and it rolls under one of the cars. The only way to retrieve it is to move the car out of the way. Depending on where the empty square is, several cars may have to move. Cars can only move forward or backward. The fence keeps every car on the lot, and blocked squares stop cars from moving through them.
Figure A.1 shows an example. An ambihelical hexnut has rolled under car 3 in row 3, column 3 (shaded dark gray). The empty square is in row 1, column 3, and the blocked square is in row 3, column 4. The only way to retrieve the part is to move car 8, then car 4, then car 3. If the empty and blocked squares were swapped, the part could not be retrieved.
Figure A.1: Sample lot. Cars 8, 4, and 3 must be moved, in that order, to uncover the grid location in row 3, column 3.
Input
The first line contains two positive integers and (), the number of rows and columns of the lot. The next lines each contain integers. The th value on the th line is the content of the square in row , column . Every value satisfies . A non-negative value means half of a junk car is in that square. Each non-negative value appears exactly twice, and the two squares are horizontally or vertically adjacent. The value -1 marks the empty square, and the value -2 marks a blocked square. There is always exactly one empty square and at least one car. There may be zero or more blocked squares.
The last line contains two integers and (), the row and column of the square to uncover. This square always holds part of a car.
Output
Print the numbers of the cars that must be moved to empty the given square, on one line separated by spaces, in the order they must be moved. If several move sequences are possible, print the shortest one. If more than one shortest sequence exists, print the one that is lexicographically first by car number. If the square cannot be uncovered, print impossible.