atcoder#AGC014C. [AGC014C] Closed Rooms
[AGC014C] Closed Rooms
Score : points
Problem Statement
Takahashi is locked within a building.
This building consists of rooms, arranged in rows and columns.
We will denote the room at the -th row and -th column as . The state of this room is represented by a character . If #
, the room is locked and cannot be entered; if .
, the room is not locked and can be freely entered.
Takahashi is currently at the room where S
, which can also be freely entered.
Each room in the -st row, -st column, -th row or -th column, has an exit. Each of the other rooms is connected to four rooms: , , and .
Takahashi will use his magic to get out of the building. In one cast, he can do the following:
- Move to an adjacent room at most times, possibly zero. Here, locked rooms cannot be entered.
- Then, select and unlock at most locked rooms, possibly zero. Those rooms will remain unlocked from then on.
His objective is to reach a room with an exit. Find the minimum necessary number of casts to do so.
It is guaranteed that Takahashi is initially at a room without an exit.
Constraints
- Each is
#
,.
orS
. - There uniquely exists such that
S
, and it satisfies and .
Input
Input is given from Standard Input in the following format:
...
:
...
Output
Print the minimum necessary number of casts.
3 3 3
#.#
#S.
###
1
Takahashi can move to room in one cast.
3 3 3
###
#S#
###
2
Takahashi cannot move in the first cast, but can unlock room . Then, he can move to room in the next cast, achieving the objective in two casts.
7 7 2
#######
#######
##...##
###S###
##.#.##
###.###
#######
2