题
思
一看就是BFS的题。
但是地图太大了,纯bfs的话会超时。
题目中正好给了blocked的大小限制,我们就让遍历足够多的节点后停下来就行了。
我也比较快的想到这点了,但是这题还是把我恶心到了。
恶心的地方就是我用红框框出的部分,去你码的,骗人!
害老子找了那么久问题,cnm!
以后用例能不能认真写一下啊leetcode。
代码
class Solution {
private int max = (int) Math.pow(10, 6);
private int maxArea = 20000;
public boolean isEscapePossible(int[][] blocked, int[] source, int[] target) {
for (int i = 0; i < blocked.length; i++) {
if ((blocked[i][0] == source[0] && blocked[i][1] == source[1])
|| (blocked[i][0] == target[0] && blocked[i][1] == target[1])) {
blocked[i][0] = -1;
blocked[i][1] = -1;
}
}
Set<String> v1 = new HashSet<String>();
Set<String> v2 = new HashSet<String>();
Queue<int[]> q1 = new LinkedList<int[]>();
Queue<int[]> q2 = new LinkedList<int[]>();
if (bfs(q1, v1, source, target, blocked) || bfs(q2, v2, target, source, blocked)) {
return true;
}
if (v1.size() > maxArea && v2.size() > maxArea) {
return true;
}
return false;
}
private boolean bfs(Queue<int[]> queue, Set<String> visited, int[] source, int[] target, int[][] blocked) {
queue.offer(source);
while (!queue.isEmpty()) {
int[] temp = queue.poll();
if (visited.contains(temp[0] + "," + temp[1])) {
continue;
}
visited.add(temp[0] + "," + temp[1]);
if (visited.size() > maxArea) {
break;
}
if (temp[0] == target[0] && temp[1] == target[1]) {
return true;
}
if (validChild(blocked, temp[0] - 1, temp[1], visited)) {
queue.offer(new int[] { temp[0] - 1, temp[1] });
}
if (validChild(blocked, temp[0] + 1, temp[1], visited)) {
queue.offer(new int[] { temp[0] + 1, temp[1] });
}
if (validChild(blocked, temp[0], temp[1] - 1, visited)) {
queue.offer(new int[] { temp[0], temp[1] - 1 });
}
if (validChild(blocked, temp[0], temp[1] + 1, visited)) {
queue.offer(new int[] { temp[0], temp[1] + 1 });
}
}
return false;
}
private boolean validChild(int[][] blocked, int x, int y, Set<String> visited) {
if (x < 0 || x >= max || y < 0 || y >= max || visited.contains(x + "," + y)) {
return false;
}
for (int[] i : blocked) {
if (i[0] == x && i[1] == y) {
return false;
}
}
return true;
}
}