File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ fun snakesAndLadders (board : Array <IntArray >): Int {
3
+ val len = board.size
4
+ board.reverse()
5
+
6
+ fun intToPos (square : Int ): Pair <Int , Int > {
7
+ val r = (square - 1 ) / len
8
+ var c = (square - 1 ) % len
9
+ if (r % 2 == 1 )
10
+ c = len - 1 - c
11
+ return r to c
12
+ }
13
+
14
+ val q = LinkedList <Pair <Int , Int >>()
15
+ q.addFirst(1 to 0 )
16
+ val visited = HashSet <Int >()
17
+ while (q.isNotEmpty()) {
18
+ val (square, moves) = q.removeLast()
19
+
20
+ for (i in 1 .. 6 ) {
21
+ var next = i + square
22
+ val (r, c) = intToPos(next)
23
+ if (board[r][c] != - 1 )
24
+ next = board[r][c]
25
+ if (next == len * len)
26
+ return moves + 1
27
+ if (next !in visited) {
28
+ visited.add(next)
29
+ q.addFirst(next to moves + 1 )
30
+ }
31
+
32
+ }
33
+ }
34
+
35
+ return - 1
36
+ }
37
+ }
You can’t perform that action at this time.
0 commit comments