Skip to content

Commit 66614c6

Browse files
committed
Time: 8 ms (99.58%), Space: 12.6 MB (86.28%) - LeetHub
1 parent 9d0c833 commit 66614c6

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
class Solution {
2+
public:
3+
pair<int,int> func(int x, int n){
4+
int r = x / n;
5+
int c = x % n;
6+
7+
int row = n - 1 - r;
8+
int col = (r % 2 == 0) ? c : (n - 1 - c);
9+
10+
return {row,col};
11+
}
12+
13+
int snakesAndLadders(vector<vector<int>>& board) {
14+
15+
int n = board.size();
16+
17+
queue<int> q;
18+
vector<int> visited(n * n + 1, 0);
19+
20+
q.push(1);
21+
visited[1] = 1;
22+
23+
int steps = -1;
24+
25+
while(!q.empty()){
26+
int sz = q.size();
27+
steps++;
28+
29+
while(sz--){
30+
int x = q.front();
31+
q.pop();
32+
33+
if(x == n * n)
34+
return steps;
35+
36+
for(int i = 1; i <= 6; i++){
37+
int v = x + i;
38+
if(v > n * n) break;
39+
pair<int,int> c = func(v - 1, n);
40+
int a = c.first, b = c.second;
41+
42+
if(board[a][b] == -1){
43+
if(!visited[v]){
44+
q.push(v);
45+
visited[v] = 1;
46+
}
47+
}
48+
49+
else{
50+
if(!visited[board[a][b]]){
51+
q.push(board[a][b]);
52+
visited[board[a][b]] = 1;
53+
// visited[v] = 1;
54+
}
55+
}
56+
57+
}
58+
}
59+
}
60+
61+
return -1;
62+
}
63+
};

0 commit comments

Comments
 (0)