一种重新映射坐标,收缩空间的解法
原题链接:Escape a Large Maze
参考自 @qb_2008 发布于讨论区的帖子
代码:
class Solution {
void gen_map(map<int, int>& a, int x) {
if (x > 0) a[x-1] = 0;
a[x] = 0;
if (x+1 < 1000000) a[x+1] = 0;
}
public:
bool isEscapePossible(vector<vector<int>>& blocked, vector<int>& source, vector<int>& target) {
map<int, int> x_map, y_map;
for (const auto& ele: blocked) {
gen_map(x_map, ele[0]), gen_map(y_map, ele[1]);
}
gen_map(x_map, source[0]), gen_map(y_map, source[1]);
gen_map(x_map, target[0]), gen_map(y_map, target[1]);
int x_size = 0, y_size = 0;
for (auto& ele: x_map) ele.second = x_size++;
for (auto& ele: y_map) ele.second = y_size++;
vector<vector<bool>> grid(x_size, vector<bool>(y_size));
for (const auto& ele: blocked) grid[x_map[ele[0]]][y_map[ele[1]]] = true;
// for (int i = 0; i < x_size; ++i) {
// for (int j = 0; j < y_size; ++j) {
// if (i == x_map[source[0]] && j == y_map[source[1]])
// cout << 2 << " ";
// else if (i == x_map[target[0]] && j == y_map[target[1]])
// cout << 3 << " ";
// else
// cout << grid[i][j] << " ";
// }
// cout << endl;
// }
queue<int> que;
que.push(x_map[source[0]] << 10 | y_map[source[1]]);
grid[x_map[source[0]]][y_map[source[1]]] = true;
static const int direc[][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
while (!que.empty()) {
int cur = que.front(); que.pop();
int x = cur >> 10, y = cur & 0x3ff;
if (x == x_map[target[0]] && y == y_map[target[1]]) return true;
for (int i = 0; i < 4; ++i) {
int nx = x + direc[i][0];
int ny = y + direc[i][1];
if (nx < 0 || nx >= x_size || ny < 0 || ny >= y_size) continue;
if (!grid[nx][ny]) {
grid[nx][ny] = true;
que.push(nx << 10 | ny);
}
}
}
return false;
}
};