The doggie found a bone in an ancient maze, which fascinated him a lot. However, when he picked it up, the maze began to shake, and the doggie could feel the ground sinking. He realized that the bone was a trap, and he tried desperately to get out of this maze.
The maze was a rectangle with sizes N by M. There was a door in the maze. At the beginning, the door was closed and it would open at the T-th second for a short period of time (less than 1 second). Therefore the doggie had to arrive at the door on exactly the T-th second. In every second, he could move one block to one of the upper, lower, left and right neighboring blocks. Once he entered a block, the ground of this block would start to sink and disappear in the next second. He could not stay at one block for more than one second, nor could he move into a visited block. Can the poor doggie survive? Please help him.
Input
The input consists of multiple test cases. The first line of each test case contains three integers N, M, and T (1 < N, M < 7; 0 < T < 50), which denote the sizes of the maze and the time at which the door will open, respectively. The next N lines give the maze layout, with each line containing M characters. A character is one of the following:
'X': a block of wall, which the doggie cannot enter;
'S': the start point of the doggie;
'D': the Door; or
'.': an empty block.
The input is terminated with three 0's. This test case is not to be processed.
Output
For each test case, print in one line "YES" if the doggie can survive, or "NO" otherwise.
Sample Input
4 4 5 S.X. ..X. ..XD .... 3 4 5 S.X. ..X. ...D 0 0 0
分析:这题用到了深度优先的递归遍历,还用到了剪枝的方法,不然超时。
剪枝内容:
1. 由于每走一格该格子会陷下去,所以每格只能走一次,也就是每个格子只能呆1s,
那么如果它所有格子都待过了门还没打开也就无解了,因此针对这种情况专门设一个剪枝,
用floodfill得到所有能走到的格子数目s,如果s<t那么可以输出无解.
2. 一个奇偶判断的法则,观察以下地图
设由红点至蓝点的最短路线是黄色虚线,那么如果不走最短路到蓝点,例如走蓝色虚线,
此时必将偏离最短路x格,若x是奇数,它必将走基数格回到最短路上,若x是偶数,它必将走
偶数格回到最短路上,那么它所走的格子数的奇偶性不会变,有墙挡住也是如此,只要绕开就行了,
但是步数的奇偶不变,所以可以先按没墙计算步数,就是两坐标之差的和.那么可以加一个剪枝,
若剩余时间为t,最短路径为x,那么若x和t的奇偶性不同则可以剪枝.
另外我没用到的剪枝:
3. 行走过程中若最短路径大于t则返回false.
前2个剪枝已经可以0.2秒ac,关于第三个剪枝,我觉得这个花费比较大,
进行bfs的最坏复杂度是O(m*n),虽然可以减掉一定的不可行分支,但同时也增加了复杂度.