Leetcode每日随机2021/3/5

在这里插入图片描述
在这里插入图片描述

一看就是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;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值