Ladder Manipulation
InterviewTime limit2sMemory limit512 MB
Given a ladder with N vertical lines, H rows, and M existing rungs, find the minimum number of rungs to add so every walk from column i ends at column i, or report -1 if more than 3.
- Level
Hard8 of 10
- Topics
- Backtracking, Brute force, Implementation, Simulation
- Solved
- No attempts yet
Problem
A ladder game is built from vertical lines and horizontal lines. A horizontal line can be placed between two adjacent vertical lines. Every vertical line has positions that can hold a horizontal line, and those positions are the same on every vertical line. The picture below shows , with no horizontal line.

The green lines are the vertical lines, and each point where a green line meets a dotted line can hold a horizontal line. A horizontal line must connect two adjacent vertical lines. Two horizontal lines must not be consecutive and must not touch each other. A horizontal line must also lie on a dotted line.

This picture has 5 horizontal lines. Each horizontal line connects two adjacent vertical lines, and it connects positions that can hold a horizontal line.
The ladder game runs separately for each vertical line and moves from the top of that vertical line downward. When the walk meets a horizontal line, it crosses to the neighboring vertical line along that horizontal line and then continues downward on the new vertical line.
In this picture, 1 ends at 3, 2 ends at 2, 3 ends at 5, 4 ends at 1, and 5 ends at 4. The two pictures below show how 1 and 2 move.
You want to change the outcome of the game by adding horizontal lines to the ladder. A walk that starts at vertical line must end at vertical line . Write a program that finds the minimum number of horizontal lines you have to add.
Input
The first line contains the number of vertical lines , the number of horizontal lines , and the number of positions on each vertical line that can hold a horizontal line. (, , )
Each of the next lines describes one horizontal line with two integers and . (, ) It means that vertical line and vertical line are connected at dotted line position .
The topmost dotted line is number 1, and the number grows by 1 for each step down. The leftmost vertical line is number 1, and the number grows by 1 for each step to the right.
No two horizontal lines given in the input are consecutive.
Output
Print the minimum number of horizontal lines you have to add so that a walk starting at vertical line ends at vertical line . If the answer is greater than 3, print -1. If it is impossible, print -1 as well.




