1
+ class VisitTracker (object ):
2
+ def __init__ (self , n ):
3
+ self .n = n
4
+ self .l = [False ,]* n
5
+ def visited (self , i ):
6
+ if i <= 0 or i > self .n :
7
+ raise ValueError ("i is out-of-bounds" )
8
+ return self .l [i - 1 ]
9
+ def setVisited (self , i ):
10
+ if i <= 0 or i > self .n :
11
+ raise ValueError ("i is out-of-bounds" )
12
+ self .l [i - 1 ] = True
13
+
14
+ class Board (object ):
15
+ def __init__ (self , ladders , snakes , maxNum = 100 ):
16
+ self .jumps = {}
17
+ # validate ladders
18
+ for a ,b in ladders :
19
+ if a >= b :
20
+ raise ValueError ("Ladders must move up" )
21
+ if a in self .jumps :
22
+ raise ValueError ("Redefinition of a jump" )
23
+ if b in self .jumps :
24
+ raise ValueError ("Cannot chain jumps" )
25
+ self .jumps [a ] = b
26
+ # validate snakes
27
+ for a ,b in snakes :
28
+ if a <= b :
29
+ raise ValueError ("Snakes must move down" )
30
+ if a in self .jumps :
31
+ raise ValueError ("Redefinition of a jump" )
32
+ if b in self .jumps :
33
+ raise ValueError ("Cannot chain jumps" )
34
+ self .jumps [a ] = b
35
+ self .maxNum = 100
36
+ def nextNums (self , currNum ):
37
+ nextNs = [currNum + die for die in xrange (1 ,7 )]
38
+ for idx , num in enumerate (nextNs [:]):
39
+ if num > self .maxNum : # prevent overflow
40
+ nextNs [idx ] = currNum
41
+ elif num in self .jumps : # ladders or snakes
42
+ nextNs [idx ] = self .jumps [num ]
43
+ return nextNs
44
+ def solve (self ):
45
+ q = [(1 ,0 ),]
46
+ v = VisitTracker (self .maxNum )
47
+ while len (q ) > 0 :
48
+ currNum , depth = q .pop (0 )
49
+ if currNum == self .maxNum :
50
+ return depth
51
+ elif not v .visited (currNum ):
52
+ v .setVisited (currNum )
53
+ for num in self .nextNums (currNum ):
54
+ q .append ((num , depth + 1 ))
55
+ return - 1
56
+
57
+
58
+ def getInputs ():
59
+ numTestcases = input ()
60
+ testcases = []
61
+ for t in xrange (numTestcases ):
62
+ ladders = []
63
+ for n in xrange (input ()):
64
+ ladders .append ([int (i ) for i in raw_input ().split (" " )])
65
+ snakes = []
66
+ for m in xrange (input ()):
67
+ snakes .append ([int (i ) for i in raw_input ().split (" " )])
68
+ testcases .append (Board (ladders , snakes ))
69
+ return testcases
70
+
71
+ if __name__ == "__main__" :
72
+ testcases = getInputs ()
73
+ for testcase in testcases :
74
+ print testcase .solve ()
0 commit comments