本文共 2026 字,大约阅读时间需要 6 分钟。
一看就是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; } } Setv1 = new HashSet (); Set v2 = new HashSet (); Queue q1 = new LinkedList (); Queue q2 = new LinkedList (); 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 queue, Set 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 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; }}
转载地址:http://fuee.baihongyu.com/