-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path909. Snakes and Ladders
47 lines (47 loc) · 1.22 KB
/
909. Snakes and Ladders
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 {
pair<int,int> coordinate(int x,int n){
int r=n-(x-1)/n-1;
int c=(x-1)%n;
if(r%2==n%2){
return {r,n-c-1};
}
return {r,c};
}
public:
int snakesAndLadders(vector<vector<int>>& board) {
int n=board.size();
int m=board[0].size();
int moves=0;
queue<int> q;
vector<vector<bool>> vis(n,vector(n,false));
vis[n-1][0]=true;
q.push(1);
while(!q.empty()){
int size=q.size();
for(int i=0;i<size;i++){
int x=q.front();
if(x==n*n){
return moves;
}
q.pop();
for(int j=1;j<=6;j++){
if(j+x>n*n){
break;
}
pair<int,int> coor=coordinate(x+j,n);
if(vis[coor.first][coor.second]){
continue;
}
vis[coor.first][coor.second]=true;
if(board[coor.first][coor.second]!=-1){
q.push(board[coor.first][coor.second]);
}else{
q.push(j+x);
}
}
}
moves++;
}
return -1;
}
};