Problem 424
Snakes and Ladders
Medium · 20 pts · Graph, Breadth-First Search
Problem
A board has cells numbered 1 to N. You start on cell 1 and roll a die that shows 1 to 6; you may choose every roll. A roll that would take you past cell N is not allowed. Some cells are the start of a ladder (which carries you up) or the head of a snake (which carries you down): if you finish a move on such a cell, you immediately jump to its other end. You only take one jump per move, even if you land on another jump's start. Find the minimum number of rolls needed to reach cell N exactly, or -1 if it cannot be reached.
Input
First line: N and J, the number of snakes and ladders. Next J lines: 'from to' for each jump.
Output
Print the minimum number of rolls, or -1.
Constraints
2 <= N <= 1000; 0 <= J <= N; jump starts are distinct and never cell 1 or cell N
Example input
30 8 3 22 5 8 11 26 20 29 17 4 19 7 21 9 27 1
Example output
3
Explanation
On a 30-cell board with ladders 3->22, 5->8, 11->26 and 20->29 and snakes 17->4, 19->7, 21->9 and 27->1: roll 2 to land on 3 and climb the ladder to 22, roll 4 to reach 26, and roll 4 again to reach 30. That is 3 rolls, and no route is shorter.