Time Limit: 1 Second Memory Limit: 32768 KB
One day, you were asked to send an important message to our friends, through a field with a lot of bombs. Because this task was too dangerous to be finished by human, a runaway robot has been given to you to do the job.
The field can be considered as an n * m grids. Now, we are at the top-left corner (0, 0), and the destination is at the bottom-right corner (n - 1, m - 1).
There is an example with a 3 * 3 field:
n = 3 ------ ------ ------ | WE | | | m | ARE | bomb | bomb | | HERE | | | ------ ------ ------ | | | | = | safe | safe | bomb | | | | | ------ ------ ------ | | | !!!! | 3 | safe | safe | HELP | | | | !!!! | ------ ------ ------
which can be represented by the matrix:
.XX ..X ...
The squares marked with '.' are safe, while 'X' means that there is a bomb in this square. Once the robot runs into a square with a bomb (marked with 'X'), the robot will get damaged immediately and the task would be failed. Square (0, 0) and square (n - 1, m - 1) are always safe.
However, the runaway robot is so simple that it can only do 2 movements: R for move right and D for down. To make thing worse, once the robot leaves the (0, 0) square, you could not send any order to it. So the orders must be kept in the memory at the beginning. Besides, the memory is too limited to store many orders. You can choose the order to become a loop, so the robot will do this task by loop order. For example, with a 2 steps loop: RD, the robot will do as RDRDRD... until it run into a square with bomb, or run out of the bound. (These two situations mean the task failed). Once the robot ran into the destination square, the task was finished.
For the above example with 3 * 3 field, there are at least two different loops can be chosen: one is 4 steps-loop DDRR, and the other is DR. Both of them can finish this task, but the second one needs less memory than the first one. The memory is so limited and expensive, you must use as little as possible.
Input
There are multiple cases (no more than 100).
Each case contains two non-negative integers n and m (1 < n, m < 101) at the first line. The following m lines each contains n characters (only '.' and 'X').
Output
For each case, output the minimum steps in a loop to finish this task. If it is impossible to finish this task, output -1.
Sample Input
2 2 .X .. 3 3 .XX ..X ... 2 2 .X X. 2 3 .. .. .. 3 3 .XX .XX ...
Sample Output
2 2 -1 2 4
算法分析:
使用宽度搜索,我在这儿使用一个vector保存所有遍历到位置,以便于读取路径。
而且vector模拟的是stack的功能。