1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| class Solution { private static final int[][] DIRS = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
private Map<Integer, Integer> idToAreaMap = new HashMap<>();
public int largestIsland(int[][] grid) { int ans = 0; int m = grid.length; int n = grid[0].length;
init(grid);
for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (0 == grid[i][j]) { List<Integer> islandIds = new ArrayList<>(); for (int[] d : DIRS) { int x = i + d[0]; int y = j + d[1]; if (isValidIdx(m, n, x, y) && grid[x][y] >= 2) { islandIds.add(grid[x][y]); } } int sum = islandIds.stream() .distinct() .map(idToAreaMap::get) .mapToInt(Integer::intValue) .sum(); ans = Math.max(ans, sum + 1); } } } return ans == 0 ? m * n : ans; }
private void init(int[][] grid) { int m = grid.length; int n = grid[0].length; int id = 2; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (1 == grid[i][j]) { int area = dfs(grid, i, j, id); idToAreaMap.put(id, area); ++id; } } } }
private int dfs(int[][] grid, int i, int j, int id) { int area = 0; int m = grid.length; int n = grid[0].length; if (!isValidIdx(m, n, i, j)) { return area; } if (grid[i][j] != 1) { return area; } grid[i][j] = id; ++area; for (int[] d : DIRS) { area += dfs(grid, i + d[0], j + d[1], id); } return area; }
private boolean isValidIdx(int m, int n, int i, int j) { return i >= 0 && i < m && j >= 0 && j < n; } }
|