1
+ import java .util .ArrayDeque ;
1
2
import java .util .Arrays ;
2
3
import java .util .HashSet ;
3
4
import java .util .LinkedList ;
4
5
import java .util .Queue ;
5
6
import java .util .Set ;
6
7
7
8
public class Solution1036 {
9
+ private static final int [][] DIRECTIONS = {{1 , 0 }, {0 , 1 }, {-1 , 0 }, {0 , -1 }};
8
10
private static final int M = 1000000 ;
9
11
private static final int N = 1000000 ;
10
12
@@ -21,33 +23,32 @@ public boolean isEscapePossible(int[][] blocked, int[] source, int[] target) {
21
23
}
22
24
23
25
private boolean bfs (int [] source , int [] target , Set <String > blockedSet ) {
24
- int [][] direction = {{1 , 0 }, {0 , 1 }, {-1 , 0 }, {0 , -1 }};
25
26
// BFS
26
- Queue <int []> queue = new LinkedList <>();
27
- Set <String > visitedSet = new HashSet <>();
28
- queue .add (source );
29
- visitedSet .add (source [0 ] + ":" + source [1 ]);
27
+ Queue <int []> q = new ArrayDeque <>();
28
+ Set <String > vis = new HashSet <>();
29
+ q .add (source );
30
+ vis .add (source [0 ] + ":" + source [1 ]);
30
31
31
- // blockedS 可以围住的最大个数
32
- int len = blockedSet .size ();
33
- int max = len * (len - 1 ) / 2 ;
32
+ // blockedSet 可以围住的最大个数
33
+ int k = blockedSet .size ();
34
+ int max = k * (k - 1 ) / 2 ;
34
35
int cnt = 0 ;
35
- while (!queue .isEmpty ()) {
36
- int size = queue .size ();
36
+ while (!q .isEmpty ()) {
37
+ int size = q .size ();
37
38
cnt += size ;
38
39
for (int i = 0 ; i < size ; i ++) {
39
- int [] cur = queue .remove ();
40
+ int [] cur = q .remove ();
40
41
// 到达目标方格
41
42
if (Arrays .equals (cur , target )) {
42
43
return true ;
43
44
}
44
- for (int [] dir : direction ) {
45
- int nextM = cur [0 ] + dir [0 ];
46
- int nextN = cur [1 ] + dir [1 ];
47
- if (nextM >= 0 && nextM < M && nextN >= 0 && nextN < N && !visitedSet .contains (nextM + ":" + nextN )
48
- && !blockedSet .contains (nextM + ":" + nextN )) {
49
- visitedSet .add (nextM + ":" + nextN );
50
- queue .add (new int []{nextM , nextN });
45
+ for (int [] d : DIRECTIONS ) {
46
+ int nx = cur [0 ] + d [0 ];
47
+ int ny = cur [1 ] + d [1 ];
48
+ if (nx >= 0 && nx < M && ny >= 0 && ny < N && !vis .contains (nx + ":" + ny )
49
+ && !blockedSet .contains (nx + ":" + ny )) {
50
+ vis .add (nx + ":" + ny );
51
+ q .add (new int []{nx , ny });
51
52
}
52
53
}
53
54
}
0 commit comments