It is easy to understand if you plot the maze. The following is the state of the maze at the end of the inputs. X
indicates that a room is closed and O
that a room is open. Note that there is no path from the top of the maze to the bottom of the maze.
O X X O
O X O X
X O X X
O X O X
Consider the second input sample (which is available if you click on the Run Code
button):
4
1 4
2 3
3 2
4 3
4 1
2 1
1 1
3 1
3 4
2 2
-1
Below is a figure with the maze after 7 rooms are open. Note that there is no path from the top of the maze to the bottom of the maze, and therefore the maze is closed.
O X X O
O X O X
X O X X
O X O X
However, after 8th room is open, there is a path, as shown below:
O X X O
O X O X
O O X X
O X O X
Thus, the expected output is: 8
-----------------------------------------------------------------------------------
Solution
Get the whole solution with Explanation (
Link)
Explanation