Snakes and Ladders
You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.
You start on square 1 of the board. In each move, starting from square curr, do the following:
- Choose a destination square
nextwith a label in the range[curr + 1, min(curr + 6, n2)].- This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.
- If
nexthas a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move tonext. - The game ends when you reach the square
n2.
A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 are not the starting points of any snake or ladder.
Note that you only take a snake or ladder at most once per dice roll. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.
- For example, suppose the board is
[[-1,4],[-1,3]], and on the first move, your destination square is2. You follow the ladder to square3, but do not follow the subsequent ladder to4.
Return the least number of dice rolls required to reach the square n2. If it is not possible to reach the square, return -1.
Example 1:

Input: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]
Output: 4
Explanation:
In the beginning, you start at square 1 (at row 5, column 0).
You decide to move to square 2 and must take the ladder to square 15.
You then decide to move to square 17 and must take the snake to square 13.
You then decide to move to square 14 and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
This is the lowest possible number of moves to reach the last square, so return 4.
Example 2:
Input: board = [[-1,-1],[-1,3]]
Output: 1
Constraints:
n == board.length == board[i].length2 <= n <= 20board[i][j]is either-1or in the range[1, n2].- The squares labeled
1andn2are not the starting points of any snake or ladder.
class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
# 1차원 배열로 바꿔서 생각하자.
# board : List[List[int]] => List[int] 로
n = len(board)
board2 = [-1]
for i in range(n-1, -1, -1) :
dr = n - i
if dr % 2 == 1 :
for j in range(n) :
board2.append(board[i][j])
else :
for j in range(n-1, -1, -1) :
board2.append(board[i][j])
start = 1
q = deque()
if board2[start] == -1 :
q.append((start, 0))
else :
q.append((board2[start], 0))
visited = [0] * len(board2)
visited[start] = 1
while q :
curr, cnt = q.popleft()
if curr == n ** 2 :
return cnt
for di in (1,2,3,4,5,6) :
nxt = board2[min(curr + di, n**2)]
if nxt == -1 and visited[min(curr + di, n**2)] == 0:
q.append((min(curr + di, n**2), cnt + 1))
visited[min(curr + di, n**2)] = 1
elif nxt != -1 and visited[min(nxt, n**2)] == 0 :
q.append((min(nxt, n**2), cnt + 1))
visited[min(nxt, n**2)] = 1
return -1
이 문제는 우리가 흔히 하는 보드 게임 뱀과 사다리 라는 게임을 구현하는 문제이다.
문제분석
- 보드에서 어디로 이동하고 행위를 하는 문제는 이차원 배열에서 일차원 배열로 만든 다음, 문제를 해결하자.
- BFS를 통해 1~6까지 다음 이동하는 것으로 만들자.
- 이동한 위치에 -1이면 주사위 숫자만큼 이동. -1이 아니면 그 위치로 이동한다.
- 그리고 이동한 횟수를 증가시키고 큐에 저장. 방문 처리
주요 풀이
- 이차원 배열의 규칙을 보면 좌측 하단에서 시작해서 우측 하단으로, 그 다음 우측 하단 한칸 위로 가고 좌측으로 이동한다. 이를 반복한다. 그래서 보드판 $N \times N$ 에서 $N$ 이 홀수냐, 짝수냐에 따라 마지막 보드판 움직이는게 달라지기 때문에 이를 구하기 위해 $N-(현재 행)$ 을 하게 되면 순서대로 일차원 배열로 만들 수 있다. 홀수일 경우 왼쪽에서 오른쪽으로, 짝수일 경우 오른쪽에서 왼쪽으로 움직이는 규칙을 확인할 수 있었다.
- 일차원 배열(board2)를 성공적으로 만들었다면, BFS를 해보자. 시작 지점에서 -1이면 start를, -1이 아니면 board2[start]를 큐에 넣는다.
- BFS를 실행한다.
- 현재위치와 주사위 굴린 횟수를 큐에서 뽑아온다.
- 정답처리 => 현재 위치가 $N*N$ 이면 종료. 주사위 굴린 횟수를 반환
- 주사위는 1부터 6까지 눈이 있는 주사위이며, 다음 위치는 board2[curr + 주사위 눈] 이 된다. 그러나 끝 부분에서 $N*N$을 초과할까봐 board2[min(curr + 주사위 눈, $N*N$)] 으로 작성하였다.
- nxt가 -1이고 (curr + 주사위눈) 위치에 미방문이라면 curr + 주사위눈 위치로 이동한다.
- nxt가 -1이 아니고 board2[curr + 주사위눈] 위치에 미방문이라면 board2[min(curr + 주사위 눈, $N*N$)] 위치로 이동한다.
- 가장 마지막 return -1은 디버깅 용으로 만들었다.
'알고리즘 스터디' 카테고리의 다른 글
| [Leetcode/파이썬] 139. Word Break (0) | 2026.01.17 |
|---|---|
| [Leetcode/파이썬] 79. Word Search (0) | 2026.01.11 |
| [Leetcode/파이썬] 19. Remove Nth Node From End of List (0) | 2026.01.01 |
| [Leetcode/파이썬] 98. Validate Binary Search Tree (0) | 2025.12.21 |
| [Leetcode/파이썬] 137. Single Number II (0) | 2025.12.21 |