-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnakes_and_ladders.cpp
More file actions
47 lines (36 loc) · 1.13 KB
/
snakes_and_ladders.cpp
File metadata and controls
47 lines (36 loc) · 1.13 KB
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
40
41
42
43
44
45
46
47
class Solution {
public:
int snakesAndLadders(vector<vector<int>>& board) {
int n = board.size();
int end = n * n;
queue<pair<int, int>> q;
unordered_set<int> visited;
q.push({1, 0});
visited.insert(1);
while(!q.empty()){
int curr = q.front().first;
int dist = q.front().second;
q.pop();
if(curr == end)
return dist;
for(int dice = 1; dice <= 6; dice++){
int next = curr + dice;
if(next > end)
break;
int r = (n - 1) - ((next - 1) / n);
int c;
if((n - 1 - r) % 2)
c = (n - 1) - (next - 1) % n;
else
c = (next - 1) % n;
if(board[r][c] != -1)
next = board[r][c];
if(visited.count(next))
continue;
q.push({next, dist + 1});
visited.insert(next);
}
}
return -1;
}
};