The Mansion
Time limit1sMemory limit256 MB
In a grid where only vertical doors start open, find the shortest time to go from (1,1) to (M,N), where holding a switch in certain rooms for a minute flips every door's state.
- Level
Medium7 of 10
- Topics
- Graph, BFS, Shortest path, Greedy
- Solved
- No attempts yet
Problem
You are trapped in a huge mansion. The mansion is a grid of square rooms with rows and columns. The room that is the -th from the left () and the -th from the bottom () is denoted .
Between every pair of adjacent rooms there is exactly one door, and each door is either open or closed. Passing through an open door into a neighboring room takes minute. You may only move through open doors, and you cannot change a door's state directly.
Some rooms have a switch at their center. Holding a switch down for minute flips the state of every door in the mansion: every open door becomes closed and every closed door becomes open.
Initially, only the doors between vertically adjacent rooms (one directly above the other) are open; all other doors are closed.
You are currently at the center of room and want to reach the center of room . Find the minimum time needed to get there.
Input
The first line contains the mansion size , and the number of rooms that have a switch, , separated by spaces. Each of the next lines contains the position , of a room that has a switch. (, )
Output
Print the minimum time to reach room on the first line. If cannot be reached, print .