-
Notifications
You must be signed in to change notification settings - Fork 0
/
Snakes _and _Ladders.cpp
32 lines (32 loc) · 1.05 KB
/
Snakes _and _Ladders.cpp
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
class Solution {
public:
int snakesAndLadders(vector<vector<int>> &board) {
int n = board.size(), lbl = 1;
vector<pair<int, int>> cells(n*n+1);
vector<int> columns(n);
iota(columns.begin(), columns.end(), 0);
for (int row = n - 1; row >= 0; row--) {
for (int column : columns) {
cells[lbl++] = {row, column};
}
reverse(columns.begin(), columns.end());
}
vector<int> dist(n*n+1, -1);
dist[1] = 0;
queue<int> q;
q.push(1);
while (!q.empty()) {
int curr = q.front();
q.pop();
for (int next = curr + 1; next <= min(curr+6, n*n); next++) {
auto [row, column] = cells[next];
int destination = board[row][column] != -1 ? board[row][column] : next;
if (dist[destination] == -1) {
dist[destination] = dist[curr] + 1;
q.push(destination);
}
}
}
return dist[n*n];
}
};