forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
the-maze.cpp
58 lines (50 loc) · 1.78 KB
/
the-maze.cpp
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
48
49
50
51
52
53
54
55
56
57
58
// Time: O(max(r, c) * w)
// Space: O(w)
class Solution {
public:
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
static const vector<vector<int>> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}};
queue<node> q;
unordered_set<int> visited;
q.emplace(0, start);
while (!q.empty()) {
int dist = 0;
vector<int> node;
tie(dist, node) = q.front();
q.pop();
if (visited.count(hash(maze, node))) {
continue;
}
if (node[0] == destination[0] &&
node[1] == destination[1]) {
return true;
}
visited.emplace(hash(maze, node));
for (const auto& dir : dirs) {
int neighbor_dist = 0;
vector<int> neighbor;
tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir);
q.emplace(dist + neighbor_dist, neighbor);
}
}
return false;
}
private:
using node = pair<int, vector<int>>;
node findNeighbor(const vector<vector<int>>& maze,
const vector<int>& node, const vector<int>& dir) {
vector<int> cur_node = node;
int dist = 0;
while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() &&
0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() &&
!maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) {
cur_node[0] += dir[0];
cur_node[1] += dir[1];
++dist;
}
return {dist, cur_node};
}
int hash(const vector<vector<int>>& maze, const vector<int>& node) {
return node[0] * maze[0].size() + node[1];
}
};