1
+ /**
2
+ * 正确思路,按最短桥的思路,从三个国家往外扩展,3个bfs
3
+ * O(row * col)
4
+ */
5
+
6
+ /**
7
+ * 方法超时
8
+ * O(row^2 * col^2)
9
+ */
10
+ class Solution {
11
+ public int miniumDistance (int [][] grid ) {
12
+ int minDistance = Integer .MAX_VALUE ;
13
+
14
+ int row = grid .length ;
15
+ int col = grid [0 ].length ;
16
+
17
+ int [][] directions = {{-1 , 0 }, {1 , 0 }, {0 , -1 }, {0 , 1 }}; // 上下左右
18
+
19
+ for (int i = 0 ; i < row ; i ++){
20
+ for (int j = 0 ; j < col ; j ++){
21
+ if (grid [i ][j ] == 0 ){
22
+ int distance = 1 ;
23
+ int curDistanceA = Integer .MAX_VALUE ; // 当前公共领土到三个国家的 max(min(distance))
24
+ int curDistanceB = Integer .MAX_VALUE ;
25
+ int curDistanceC = Integer .MAX_VALUE ;
26
+
27
+ boolean [][] visited = new boolean [row ][col ]; // 判断是否访问过
28
+
29
+ Queue <int []> queue = new LinkedList <>();
30
+
31
+ queue .offer (new int []{i , j });
32
+
33
+ visited [i ][j ] = true ;
34
+
35
+ pointA : while (!queue .isEmpty ()){
36
+ int size = queue .size ();
37
+ while (size -- > 0 ){
38
+ int [] loc = queue .poll ();
39
+ int x = loc [0 ];
40
+ int y = loc [1 ];
41
+ for (int [] direction : directions ){
42
+ int new_x = x + direction [0 ];
43
+ int new_y = y + direction [1 ];
44
+ if (new_x >= 0 && new_x < row && new_y >= 0 && new_y < col ){
45
+ if (visited [new_x ][new_y ] == false ){
46
+ queue .offer (new int []{new_x , new_y });
47
+ visited [new_x ][new_y ] = true ;
48
+
49
+ if (grid [new_x ][new_y ] == 1 && curDistanceA == Integer .MAX_VALUE ){
50
+ curDistanceA = distance ;
51
+ }else if (grid [new_x ][new_y ] == 2 && curDistanceB == Integer .MAX_VALUE ){
52
+ curDistanceB = distance ;
53
+ }else if (grid [new_x ][new_y ] == 3 && curDistanceC == Integer .MAX_VALUE ){
54
+ curDistanceC = distance ;
55
+ }
56
+ if (curDistanceA != Integer .MAX_VALUE && curDistanceB != Integer .MAX_VALUE && curDistanceC != Integer .MAX_VALUE ){
57
+ break pointA ;
58
+ }
59
+ }
60
+ }
61
+ }
62
+
63
+ }
64
+ distance ++;
65
+ }
66
+
67
+ distance = Math .max (Math .max (curDistanceA , curDistanceB ), curDistanceC ); // 最大距离
68
+ minDistance = Math .min (minDistance , distance ); // 最小
69
+ }
70
+ }
71
+ }
72
+
73
+ return minDistance ;
74
+ }
75
+ }
0 commit comments