[LeetCode] Snakes and Ladders

909. Snakes and Ladders

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 number x+1, x+2, x+3, x+4, x+5, or x+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 to S.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
unordered_map<int, pair<int, int>> build(int n) {
unordered_map<int, pair<int, int>> res;
int index = 1;
for(int i = n - 1; i >= 0; i--) {
for(int j = !((n - i + 1) % 2) ? 0 : n - 1; j != -1 && j != n; j += !((n - i + 1) % 2) ? 1 : -1) {
res[index++] = {i, j};
}
}
return res;
}
public:
int snakesAndLadders(vector<vector<int>>& board) {
int n = board.size();
unordered_map<int, pair<int, int>> m = build(n);
if(board[m[n*n].first][m[n*n].second] != -1) return -1;
queue<pair<int, int>> q;
q.push({1, 0});

while(!q.empty()) {
auto p = q.front();
q.pop();
if(p.first + 6 >= n * n) return p.second + 1;
for(int i = p.first + 1; i <= p.first + 6; i++) {
if(m.count(i)) {
auto pos = m[i];
if(board[pos.first][pos.second] == n * n) return p.second + 1;
q.push({board[pos.first][pos.second] == -1 ? i : board[pos.first][pos.second], p.second + 1});
m.erase(i);
}
}
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/23/PS/LeetCode/snakes-and-ladders/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.