Skip to content

Commit dddb4b7

Browse files
authored
Create 0909-snakes-and-ladders.kt
1 parent 9b6893d commit dddb4b7

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

kotlin/0909-snakes-and-ladders.kt

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
}

0 commit comments

Comments
 (0)