Skip to content

Commit 4f05440

Browse files
authored
Merge pull request doocs#301 from AudiVehicle/master
add solution for leetcode 1036
2 parents 47e8c88 + 8d358ba commit 4f05440

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution {
2+
3+
private static final int[] dx = {0, 0, -1, 1};
4+
private static final int[] dy = {1, -1, 0, 0};
5+
6+
7+
public boolean isEscapePossible(int[][] blocked, int[] source, int[] target) {
8+
if (blocked.length < 2) {
9+
return Boolean.TRUE;
10+
}
11+
12+
return walk(blocked, source, target) && walk(blocked, target, source);
13+
}
14+
15+
private Boolean walk(int[][] blocked, int[] source, int[] target) {
16+
int N = 1000000;
17+
18+
Set<Pair<Integer, Integer>> visitSet = new HashSet<>();
19+
Queue<Pair<Integer, Integer>> queue = new LinkedList<>();
20+
21+
Pair<Integer, Integer> start = new Pair<>(source[0], source[1]);
22+
queue.add(start);
23+
visitSet.add(start);
24+
25+
Set<Pair> blockedSet = Arrays.stream(blocked).map(item -> new Pair(item[0], item[1])).collect(Collectors.toSet());
26+
27+
while (!queue.isEmpty()) {
28+
Pair<Integer, Integer> top = queue.poll();
29+
Integer x = top.getKey();
30+
Integer y = top.getValue();
31+
32+
for (int i = 0; i < 4; i++) {
33+
int newY = y + dy[i];
34+
int newX = x + dx[i];
35+
Pair<Integer, Integer> pair = new Pair<>(newX, newY);
36+
if (newX < 0 || newY < 0 || newX >= N || newY >= N || visitSet.contains(pair) || blockedSet.contains(pair)) {
37+
continue;
38+
}
39+
queue.add(pair);
40+
visitSet.add(pair);
41+
if (queue.size() >= blocked.length || (newX == target[0] && newY == target[1])) {
42+
return Boolean.TRUE;
43+
}
44+
}
45+
}
46+
return Boolean.FALSE;
47+
}
48+
}

0 commit comments

Comments
 (0)