1
+ // Runtime: 93 ms (Top 5.05%) | Memory: 72.8 MB (Top 5.08%)
1
2
class Solution {
2
3
public int maxAreaOfIsland (int [][] grid ) {
3
-
4
+
4
5
final int rows =grid .length ;
5
6
final int cols =grid [0 ].length ;
6
7
final int [][] dirrections =new int [][]{{1 ,0 },{0 ,1 },{-1 ,0 },{0 ,-1 }};
7
- Map <String ,List <int []>> adj =new HashMap <>();
8
+ Map <String ,List <int []>> adj =new HashMap <>();
8
9
boolean [][] visited =new boolean [rows ][cols ];
9
10
Queue <String > queue =new LinkedList <>();
10
11
int res =0 ;
11
-
12
+
12
13
for (int i =0 ;i <grid .length ;i ++)
13
14
{
14
15
for (int j =0 ;j <grid [i ].length ;j ++)
15
16
{
16
-
17
+
17
18
List <int []> list =new ArrayList <>();
18
19
for (int [] dirrection :dirrections )
19
20
{
20
21
int newRow =dirrection [0 ]+i ;
21
22
int newCol =dirrection [1 ]+j ;
22
-
23
+
23
24
boolean isInBoard =newRow >=rows ||newRow <0 ||newCol >=cols ||newCol <0 ;
24
25
if (!isInBoard )
25
26
{
26
27
list .add (new int []{newRow ,newCol ,grid [newRow ][newCol ]});
27
28
}
28
29
}
29
-
30
+
30
31
adj .put (getNodeStringFormat (i ,j ,grid [i ][j ]),list );
31
32
}
32
- }
33
-
33
+ }
34
+
34
35
for (int i =0 ;i <rows ;i ++)
35
36
{
36
37
for (int j =0 ;j <cols ;j ++)
@@ -43,10 +44,10 @@ public int maxAreaOfIsland(int[][] grid) {
43
44
{
44
45
String currentStr =queue .poll ();
45
46
String [] current =currentStr .split ("," );
46
-
47
+
47
48
int row =Integer .valueOf (current [0 ]);
48
49
int col =Integer .valueOf (current [1 ]);
49
- int isLand =Integer .valueOf (current [2 ]);
50
+ int isLand =Integer .valueOf (current [2 ]);
50
51
if (!adj .containsKey (currentStr ))
51
52
continue ;
52
53
if (visited [row ][col ])
@@ -61,14 +62,14 @@ public int maxAreaOfIsland(int[][] grid) {
61
62
int newIsLand =item [2 ];
62
63
if (!visited [newRow ][newCol ] && newIsLand ==1 && isLand ==1 )
63
64
queue .add (getNodeStringFormat (newRow ,newCol ,newIsLand ));
64
- }
65
+ }
65
66
}
66
67
res =Math .max (res ,count );
67
68
}
68
69
}
69
-
70
+
70
71
return res ;
71
-
72
+
72
73
}
73
74
private String getNodeStringFormat (int row ,int col ,int isLand )
74
75
{
@@ -80,4 +81,4 @@ private String getNodeStringFormat(int row,int col,int isLand)
80
81
sb .append (isLand );
81
82
return sb .toString ();
82
83
}
83
- }
84
+ }
0 commit comments