Skip to content

Commit 0d4384b

Browse files
committed
May 31
1 parent 3b417e6 commit 0d4384b

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

2025-05-May-LeetCoding-Challenge/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,12 @@
3434
| May 28 | [3372. Maximize the Number of Target Nodes After Connecting Trees I](https://leetcode.com/problems/maximize-the-number-of-target-nodes-after-connecting-trees-i/) | Medium | Solved |
3535
| May 29 | [3373. Maximize the Number of Target Nodes After Connecting Trees II](https://leetcode.com/problems/maximize-the-number-of-target-nodes-after-connecting-trees-ii/) | Hard | Unsolved |
3636
| May 30 | [2359. Find Closest Node to Given Two Nodes](https://leetcode.com/problems/find-closest-node-to-given-two-nodes/) | Medium | Solved |
37-
| May 31 | []() | | |
37+
| May 31 | [909. Snakes and Ladders](https://leetcode.com/problems/snakes-and-ladders/) | Medium | Solved |
3838

3939

4040
## Summary
4141
| Level | Problems | Solved | Unsolved |
4242
| --- | --- | --- | --- |
4343
| Easy | 7 | 7 | 0 |
44-
| Medium | 15 | 12 | 3 |
44+
| Medium | 16 | 13 | 3 |
4545
| Hard | 7 | 1 | 6 |
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
from collections import deque
2+
3+
4+
class Solution:
5+
def __init__(self):
6+
self.n = 0
7+
8+
def __get_coordinates(self, position: int) -> tuple[int, int]:
9+
row = (position - 1) // self.n
10+
col = (position - 1) % self.n
11+
if row % 2 == 1:
12+
col = self.n - 1 - col
13+
return self.n - 1 - row, col
14+
15+
def snakesAndLadders(self, board: list[list[int]]) -> int:
16+
self.n = len(board)
17+
queue = deque([(1, 0)]) # (position, moves)
18+
visited = {1}
19+
while queue:
20+
position, moves = queue.popleft()
21+
if position == self.n * self.n:
22+
return moves
23+
for move in range(1, 7):
24+
new_position = position + move
25+
if new_position > self.n * self.n:
26+
continue
27+
row, col = self.__get_coordinates(new_position)
28+
if board[row][col] != -1:
29+
new_position = board[row][col]
30+
if new_position not in visited:
31+
queue.append((new_position, moves + 1))
32+
visited.add(new_position)
33+
return -1
34+
35+
36+
def main():
37+
board = [[-1, -1, -1, -1, -1, -1],
38+
[-1, -1, -1, -1, -1, -1],
39+
[-1, -1, -1, -1, -1, -1],
40+
[-1, 35, -1, -1, 13, -1],
41+
[-1, -1, -1, -1, -1, -1],
42+
[-1, 15, -1, -1, -1, -1]]
43+
assert Solution().snakesAndLadders(board) == 4
44+
45+
board = [[-1, -1],
46+
[-1, 3]]
47+
assert Solution().snakesAndLadders(board) == 1
48+
49+
50+
if __name__ == '__main__':
51+
main()

0 commit comments

Comments
 (0)