-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path909. Snakes and Ladders (Leetcode)
39 lines (39 loc) · 1.2 KB
/
909. Snakes and Ladders (Leetcode)
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
37
38
39
class Solution {
public:
int snakesAndLadders(vector<vector<int>>& board) {
int n = board.size();
int k = 1;
int jumpTo[(n * n) + 1];
vector<bool> visited((n * n) + 1, false);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(board[n - 1 - i][i % 2 == 0? j: n - 1 - j] == -1)
jumpTo[k] = k;
else
jumpTo[k] = board[n - 1 - i][i % 2 == 0? j: n - 1 - j];
k++;
}
}
int moves = 0;
queue<int> Queue;
Queue.push(1);
visited[1] = true;
while(!Queue.empty()) {
int sz = Queue.size();
for(int i = 0; i < sz; i++) {
int curr = Queue.front();
Queue.pop();
if(curr == n * n) return moves;
for(int j = curr + 1; j <= min(curr + 6, n * n); j++) {
int next = jumpTo[j];
if(visited[next] == false) {
visited[next] = true;
Queue.push(next);
}
}
}
moves++;
}
return -1;
}
};