Skip to content

Commit e78fd79

Browse files
authored
Create snakes-and-ladders.cpp
1 parent 8a471ab commit e78fd79

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

C++/snakes-and-ladders.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(n^2)
2+
// Space: O(n^2)
3+
4+
class Solution {
5+
public:
6+
int snakesAndLadders(vector<vector<int>>& board) {
7+
const int n = board.size();
8+
unordered_map<int, int> lookup;
9+
lookup[1] = 0;
10+
queue<int> q({1});
11+
while (!q.empty()) {
12+
const auto s = q.front(); q.pop();
13+
if (s == n * n) {
14+
return lookup[s];
15+
}
16+
for (int i = s + 1; i < min(s + 6, n * n) + 1; ++i) {
17+
int r, c;
18+
tie(r, c) = coordinate(n, i);
19+
int s2 = i;
20+
if (board[r][c] != -1) {
21+
s2 = board[r][c];
22+
}
23+
if (!lookup.count(s2)) {
24+
lookup[s2] = lookup[s] + 1;
25+
q.emplace(s2);
26+
}
27+
}
28+
}
29+
return -1;
30+
}
31+
32+
private:
33+
pair<int, int> coordinate(int n, int s) {
34+
const int a = (s - 1) / n;
35+
const int b = (s - 1) % n;
36+
const int r = n - 1 - a;
37+
const int c = (r % 2 != n % 2) ? b : n - 1 - b;
38+
return {r, c};
39+
}
40+
};

0 commit comments

Comments
 (0)