Store-Keeper
Time limit1sMemory limit128 MB
On an n by m grid of cases and empty fields, the keeper walks and pushes a parcel; find the minimum number of pushes to reach the target field.
- Level
Medium7 of 10
- Topics
- BFS, Graph, Shortest path, Implementation
- Solved
- No attempts yet
Problem
The floor of a store is a rectangle divided into square fields. Two fields are adjacent if they share a common side. A parcel lies on one of the fields. Each of the remaining fields is either empty or occupied by a case that is too heavy for the store-keeper to move. The store-keeper must shift the parcel from its starting field to the target field.
The store-keeper walks on empty fields, moving one step at a time from the field he stands on to an adjacent empty field. When the store-keeper stands on a field adjacent to the parcel, he may push the parcel so that it moves to the field on the opposite side of the parcel, provided that field does not hold a case.
Write a program that:
- reads a store map, the starting position of the store-keeper, and the target position of the parcel from standard input,
- computes the minimum number of parcel pushes (the number of times the parcel crosses a field border) needed to place the parcel on the target field, or decides that this is impossible,
- writes the result to standard output.
Input
The first line contains two positive integers and () separated by a single space, the dimensions of the store. Each of the next lines contains one string of length made of the letters S, M, P, K, w. The -th character of the -th line denotes the type of the field with coordinates :
- S: a case,
- M: the starting position of the store-keeper,
- P: the starting position of the parcel,
- K: the target position of the parcel,
- w: an empty field.
Each of the letters M, P, and K appears exactly once.
Output
Print to standard output:
- the single word NIE (Polish for "no") if the parcel cannot be placed on the target field,
- otherwise a single integer equal to the minimum number of parcel pushes (the number of times the parcel crosses a field border) needed to place the parcel on the target field.