Skip to content

Commit ac57988

Browse files
authored
Create minimum-moves-to-reach-target-with-rotations.cpp
1 parent 82a2573 commit ac57988

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
private:
6+
template <typename A, typename B, typename C>
7+
struct TupleHash {
8+
size_t operator()(const tuple<A, B, C>& p) const {
9+
size_t seed = 0;
10+
A a; B b; C c;
11+
tie(a, b, c) = p;
12+
seed ^= std::hash<A>{}(a) + 0x9e3779b9 + (seed<<6) + (seed>>2);
13+
seed ^= std::hash<B>{}(b) + 0x9e3779b9 + (seed<<6) + (seed>>2);
14+
seed ^= std::hash<C>{}(c) + 0x9e3779b9 + (seed<<6) + (seed>>2);
15+
return seed;
16+
}
17+
};
18+
19+
public:
20+
int minimumMoves(vector<vector<int>>& grid) {
21+
int level = 0;
22+
vector<tuple<int, int, bool>> q = {{0, 0, false}};
23+
unordered_set<tuple<int, int, bool>, TupleHash<int, int, bool>> lookup;
24+
while (!q.empty()) {
25+
vector<tuple<int, int, bool>> next_q;
26+
for (const auto& [r, c, is_vertical] : q) {
27+
if (lookup.count(make_tuple(r, c, is_vertical))) {
28+
continue;
29+
}
30+
if (make_tuple(r, c, is_vertical) ==
31+
make_tuple(grid.size() - 1, grid.size() - 2, false)) {
32+
return level;
33+
}
34+
lookup.emplace(r, c, is_vertical);
35+
if (!is_vertical) {
36+
if (c + 2 != grid[0].size() && grid[r][c + 2] == 0) {
37+
next_q.emplace_back(r, c + 1, is_vertical);
38+
}
39+
if (r + 1 != grid.size() &&
40+
grid[r + 1][c] == 0 && grid[r + 1][c + 1] == 0) {
41+
next_q.emplace_back(r + 1, c, is_vertical);
42+
next_q.emplace_back(r, c, !is_vertical);
43+
}
44+
} else {
45+
if (r + 2 != grid.size() && grid[r + 2][c] == 0) {
46+
next_q.emplace_back(r + 1, c, is_vertical);
47+
}
48+
if (c + 1 != grid[0].size() &&
49+
grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0) {
50+
next_q.emplace_back(r, c + 1, is_vertical);
51+
next_q.emplace_back(r, c, !is_vertical);
52+
}
53+
}
54+
}
55+
q = move(next_q);
56+
++level;
57+
}
58+
return -1;
59+
}
60+
};

0 commit comments

Comments
 (0)