Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/909.html
909. Snakes and Ladders
Level
Medium
Description
On an N x N board
, the numbers from 1
to N*N
are written boustrophedonically starting from the bottom left of the board, and alternating direction each row. For example, for a 6 x 6 board, the numbers are written as follows:
You start on square 1
of the board (which is always in the last row and first column). Each move, starting from square x
, consists of the following:
- You choose a destination square
S
with numberx+1
,x+2
,x+3
,x+4
,x+5
, orx+6
, provided this number is<= N*N
.- (This choice simulates the result of a standard 6-sided die roll: ie., there are always at most 6 destinations, regardless of the size of the board.)
- If
S
has a snake or ladder, you move to the destination of that snake or ladder. Otherwise, you move toS
.
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]
.
Note that you only take a snake or ladder at most once per move: if the destination to a snake or ladder is the start of another snake or ladder, you do not continue moving. (For example, if the board is [[4,-1],[-1,3]]
, and on the first move your destination square is 2
, then you finish your first move at 3
, because you do not continue moving to 4
.)
Return the least number of moves required to reach square N*N. If it is not possible, return -1
.
Example 1:
Input: [
[-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:
At 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 (row 3, column 5), 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.
It can be shown that you need at least 4 moves to reach the N*N-th square, so the answer is 4.
Note:
2 <= board.length = board[0].length <= 20
board[i][j]
is between1
andN*N
or is equal to-1
.- The board square with number
1
has no snake or ladder. - The board square with number
N*N
has no snake or ladder.
Solution
First, use a map to store each square number and the value on the square number.
Next, do breadth first search starting from square 1. Starting from each square, there are at most 6 reachable squares. For each square, maintain two states, which are whether the square has been reached by a normal move and whether the square has been reached by a “snake or ladder”. If the square is reached for the first time under the current state, then add the square to the queue for the next step’s search. Once the square NN is reached, return the number of moves. If the square NN is never reached, return -1.
-
class Solution { public int snakesAndLadders(int[][] board) { Map<Integer, Integer> cellValueMap = new HashMap<Integer, Integer>(); int sideLength = board.length; int cellsCount = sideLength * sideLength; int direction = 1; int row = sideLength - 1, column = 0; for (int i = 1; i <= cellsCount; i++) { cellValueMap.put(i, board[row][column]); if (i % sideLength == 0) { row--; direction *= -1; } else column += direction; } int moves = 0; int[] visits = new int[cellsCount + 1]; visits[1] = 1; Queue<Integer> queue = new LinkedList<Integer>(); queue.offer(1); while (!queue.isEmpty()) { moves++; int size = queue.size(); for (int i = 0; i < size; i++) { int cell = queue.poll(); int maxCell = Math.min(cell + 6, cellsCount); for (int j = cell + 1; j <= maxCell; j++) { if (j == cellsCount) return moves; int value = cellValueMap.get(j); if (value == -1) { if ((visits[j] & 1) == 0) { visits[j]++; queue.offer(j); } } else { if (value == cellsCount) return moves; if ((visits[value] & 2) == 0) { visits[value] += 2; queue.offer(value); } } } } } return -1; } }
-
// OJ: https://leetcode.com/problems/snakes-and-ladders/ // Time: O(N^2) // Space: O(N^2) class Solution { public: int snakesAndLadders(vector<vector<int>>& A) { int N = A.size(), step = 0; vector<bool> seen(N * N + 1); seen[1] = true; queue<int> q{ {1} }; while (q.size()) { int cnt = q.size(); while (cnt--) { int u = q.front(); if (u == N * N) return step; q.pop(); for (int v = u + 1; v <= min(N * N, u + 6); ++v) { int x = (v - 1) / N, y = (v - 1) % N; if (x % 2) y = N - 1 - y; x = N - 1 - x; int next = A[x][y] == -1 ? v : A[x][y]; if (seen[next]) continue; seen[next] = true; q.push(next); } } ++step; } return -1; } };
-
class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: def get(x): i, j = (x - 1) // n, (x - 1) % n if i & 1: j = n - 1 - j return n - 1 - i, j n = len(board) q = deque([1]) vis = {1} ans = 0 while q: for _ in range(len(q)): curr = q.popleft() if curr == n * n: return ans for next in range(curr + 1, min(curr + 7, n * n + 1)): i, j = get(next) if board[i][j] != -1: next = board[i][j] if next not in vis: q.append(next) vis.add(next) ans += 1 return -1
-
func snakesAndLadders(board [][]int) int { n := len(board) get := func(x int) []int { i, j := (x-1)/n, (x-1)%n if i%2 == 1 { j = n - 1 - j } return []int{n - 1 - i, j} } q := []int{1} vis := make([]bool, n*n+1) vis[1] = true ans := 0 for len(q) > 0 { for t := len(q); t > 0; t-- { curr := q[0] if curr == n*n { return ans } q = q[1:] for k := curr + 1; k <= curr+6 && k <= n*n; k++ { p := get(k) next := k i, j := p[0], p[1] if board[i][j] != -1 { next = board[i][j] } if !vis[next] { vis[next] = true q = append(q, next) } } } ans++ } return -1 }