题目
在一个 10^6 x 10^6 的网格中,每个网格上方格的坐标为 (x, y) 。
现在从源方格 source = [sx, sy] 开始出发,意图赶往目标方格 target = [tx, ty] 。数组 blocked 是封锁的方格列表,其中每个 blocked[i] = [xi, yi] 表示坐标为 (xi, yi) 的方格是禁止通行的。
每次移动,都可以走到网格中在四个方向上相邻的方格,只要该方格 不 在给出的封锁列表 blocked 上。同时,不允许走出网格。
只有在可以通过一系列的移动从源方格 source 到达目标方格 target 时才返回 true。否则,返回 false。
解题思路
离散化+BFS。由于点的数量很少,但是数据范围很大,直接搜索必定TLE。最常用的做法是将其横坐标和纵坐标进行离散化,重新建图再进行搜索。
需要注意的是,离散化的时候,需要将每个障碍点相邻的四个点都丢进去,不然会出现就算相邻的很远,也会闭环的情况,开始的时候没注意这个,WA在了第25组样例,我把图打出来发现,竟然是个闭环的菱形。后来想到了把给出的障碍点周围的点加进去,以表空隙。
离散化建图之后,剩下的就是BFS了,最基础的BFS。
代码
class Node {
int x, y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
class Solution {
public static final int MAX_LENGTH = 600 + 50;
public static final int[][] turn = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
public static final int MAX_POINT_VALUE = 1000000;
int[][] pic = new int[MAX_LENGTH][MAX_LENGTH];
boolean[][] flag = new boolean[MAX_LENGTH][MAX_LENGTH];
Map<Integer, Integer> vertical = new TreeMap<>();
Map<Integer, Integer> horizontal = new TreeMap<>();
public boolean isEscapePossible(int[][] blocked, int[] source, int[] target) {
initPic(blocked, source, target);
return bfs(source, target);
}
private boolean bfs(int[] source, int[] target) {
Node begin_node = new Node(vertical.get(source[0]), horizontal.get(source[1]));
Node end_node = new Node(vertical.get(target[0]), horizontal.get(target[1]));
Queue<Node> queue = new ArrayDeque<>();
flag[begin_node.x][begin_node.y] = true;
queue.add(begin_node);
while (!queue.isEmpty()) {
Node now = queue.poll();
if (now.x == end_node.x && now.y == end_node.y) {
return true;
}
for (int i = 0; i < 4; i++) {
Node next = new Node(now.x + turn[i][0], now.y + turn[i][1]);
if (judge(next)) continue;
flag[next.x][next.y] = true;
queue.add(next);
}
}
return false;
}
private boolean judge(Node next) {
if (next.x < 1 || next.x > vertical.keySet().size() || next.y < 1 || next.y > horizontal.keySet().size())
return true;
if (pic[next.x][next.y] == 1) return true;
return flag[next.x][next.y];
}
private void initPic(int[][] blocked, int[] source, int[] target) {
vertical.put(source[0], 1);
vertical.put(target[0], 1);
horizontal.put(source[1], 1);
horizontal.put(target[1], 1);
for (int[] ints : blocked) {
vertical.put(ints[0], 1);
if (ints[0] > 0) vertical.put(ints[0] - 1, 1);
if (ints[0] < MAX_POINT_VALUE - 1) vertical.put(ints[0] + 1, 1);
horizontal.put(ints[1], 1);
if (ints[1] > 0) horizontal.put(ints[1] - 1, 1);
if (ints[1] < MAX_POINT_VALUE - 1) horizontal.put(ints[1] + 1, 1);
}
int cnt_ver = 1, cnt_hor = 1;
for (Integer ver : vertical.keySet()) {
vertical.put(ver, cnt_ver++);
}
for (Integer hor : horizontal.keySet()) {
horizontal.put(hor, cnt_hor++);
}
for (int[] ints : blocked) {
pic[vertical.get(ints[0])][horizontal.get(ints[1])] = 1;
}
}
}