Max Area of Island LeetCode solution in Java

1
class Solution {
2
public int maxAreaOfIsland(int[][] grid) {
3

4
final int rows = grid.length;
5
final int cols = grid[0].length;
6
final int[][] dirrections = new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
7
Map<String, List<int[]>> adj = new HashMap<>();
8
boolean[][] visited = new boolean[rows][cols];
9
Queue<String> queue = new LinkedList<>();
10
int res = 0;
11

12
for (int i = 0; i < grid.length; i++) {
13
for (int j = 0; j < grid[i].length; j++) {
14

15
List<int[]> list = new ArrayList<>();
16
for (int[] dirrection : dirrections) {
17
int newRow = dirrection[0] + i;
18
int newCol = dirrection[1] + j;
19

20
boolean isInBoard = newRow >= rows || newRow < 0 || newCol >= cols || newCol < 0;
21
if (!isInBoard) {
22
list.add(new int[] {newRow, newCol, grid[newRow][newCol]});
23
}
24
}
25

26
adj.put(getNodeStringFormat(i, j, grid[i][j]), list);
27
}
28
}
29

30
for (int i = 0; i < rows; i++) {
31
for (int j = 0; j < cols; j++) {
32
int count = 0;
33
if (visited[i][j]) continue;
34
queue.add(getNodeStringFormat(i, j, grid[i][j]));
35
while (!queue.isEmpty()) {
36
String currentStr = queue.poll();
37
String[] current = currentStr.split(",");
38

39
int row = Integer.valueOf(current[0]);
40
int col = Integer.valueOf(current[1]);
41
int isLand = Integer.valueOf(current[2]);
42
if (!adj.containsKey(currentStr)) continue;
43
if (visited[row][col]) continue;
44
if (isLand == 1) count++;
45
visited[row][col] = true;
46
for (int[] item : adj.get(currentStr)) {
47
int newRow = item[0];
48
int newCol = item[1];
49
int newIsLand = item[2];
50
if (!visited[newRow][newCol] && newIsLand == 1 && isLand == 1)
51
queue.add(getNodeStringFormat(newRow, newCol, newIsLand));
52
}
53
}
54
res = Math.max(res, count);
55
}
56
}
57

58
return res;
59
}
60

61
private String getNodeStringFormat(int row, int col, int isLand) {
62
StringBuilder sb = new StringBuilder();
63
sb.append(row);
64
sb.append(",");
65
sb.append(col);
66
sb.append(",");
67
sb.append(isLand);
68
return sb.toString();
69
}
70
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0