Go around the Labyrinth
InterviewTime limit2sMemory limit512 MB
Decide whether a walk from the top-left corner can visit the other three corners and come back, where each non-entrance room collapses after one visit.
- Level
Medium6 of 10
- Topics
- Graph, DFS, Backtracking, Implementation
- Solved
- No attempts yet
Problem
Explorer Taro got the floor plan of a labyrinth. The floor is a two dimensional grid, and each cell of the plan is one room marked as enterable or not. The labyrinth has a single entrance at the northwest corner, which is the upper left cell of the plan. A treasure chest sits in each of the other three corner rooms, at the southwest, the southeast and the northeast. To get a chest, Taro has to move onto the room where the chest is placed.
Taro starts from the entrance room and repeats moving to one of the enterable adjacent rooms in the four directions, north, south, east or west. He wants to collect all three chests and come back to the entrance room. The bad news is that the labyrinth is quite dilapidated. Except for the entrance room, the floor of an enterable room is so fragile that it collapses once Taro has passed over it, and a collapsed room is no longer enterable. The entrance room never collapses. Determine whether Taro can collect all three treasure chests and return to the entrance.
Input
The input consists of at most 100 datasets, each in the following format.
N M
c1,1...c1,M
...
cN,1...cN,M
The first line contains , the number of rooms in the north to south direction, and , the number of rooms in the east to west direction. and are integers satisfying and . Each of the following lines contains a string of length . The -th character of the -th string represents the state of the room , the -th from the northernmost and the -th from the westernmost. The character is a period (.) if the room is enterable and a number sign (#) if it is not. The entrance is the room , and the treasure chests are placed in the rooms , and . All four of these rooms are enterable. Taro cannot go outside the given rooms.
A line containing two zeros indicates the end of the input.
Output
For each dataset, print YES in a single line if Taro can collect all three treasure chests and return to the entrance room, and NO otherwise.