-
Notifications
You must be signed in to change notification settings - Fork 0
/
Snake and ladder
34 lines (34 loc) · 963 Bytes
/
Snake and ladder
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
class Solution {
public:
int snakesAndLadders(vector<vector<int>>& board) {
int n = board.size();
int steps = 0;
queue<int> q;
vector<vector<bool>> visited(n, vector<bool>(n, false));
q.push(1);
visited[n-1][0] = true;
while (!q.empty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
int f = q.front();
q.pop();
if (f == n*n) return steps;
for (int k = 1; k <= 6; k++) {
int curr=k+f;
if (curr > n*n) break;
int r = n - (curr - 1) / n -1;
int c = (r%2==n%2)?n-1-(curr-1)%n:(curr-1)%n;
if (visited[r][c]) continue;
visited[r][c] = true;
if (board[r][c] == -1) {
q.push(curr);
} else {
q.push(board[r][c]);
}
}
}
steps++;
}
return -1;
}
};