Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- private static final int[] dirY = {0, 0, 1, -1};
- private static final int[] dirX = {1, -1, 0, 0};
- private static final int NOT_VISITED = 1;
- private static final int WATER = 0;
- public int largestIsland(int[][] grid) {
- int n = grid.length;
- int maxIslandSize = 0;
- int[] componentSizes = new int[2 + n * n];
- List<Zero> zeroes = new LinkedList<>();
- int nextComponent = 2;
- for (int y = 0; y < n; y++) {
- for (int x = 0; x < n; x++) {
- if (grid[y][x] == NOT_VISITED) {
- int component = nextComponent++;
- grid[y][x] = component;
- goDeep(y, x, grid, componentSizes);
- maxIslandSize = Math.max(maxIslandSize, componentSizes[component]);
- } else if (grid[y][x] == WATER) {
- zeroes.add(new Zero(y, x));
- }
- }
- }
- Set<Integer> processedComponents = new HashSet<>(6);
- for(Zero zero : zeroes) {
- int newIslandSize = 1;
- for (int dir = 0; dir < 4; dir++) {
- int y2 = zero.y + dirY[dir];
- int x2 = zero.x + dirX[dir];
- if (isOnGrid(y2, x2, grid)) {
- int component = grid[y2][x2];
- if (component != WATER && processedComponents.add(component)) {
- newIslandSize += componentSizes[component];
- }
- }
- }
- maxIslandSize = Math.max(maxIslandSize, newIslandSize);
- processedComponents.clear();
- }
- return maxIslandSize;
- }
- private void goDeep(int y, int x, int[][] grid, int[] sizes) {
- int component = grid[y][x];
- sizes[component]++;
- for (int dir = 0; dir < 4; dir++) {
- int y2 = y + dirY[dir];
- int x2 = x + dirX[dir];
- if (isOnGrid(y2, x2, grid) && grid[y2][x2] == NOT_VISITED) {
- grid[y2][x2] = component;
- goDeep(y2, x2, grid, sizes);
- }
- }
- }
- private boolean isOnGrid(int y, int x, int[][] grid) {
- return 0 <= y && y < grid.length && 0 <= x && x < grid.length;
- }
- private static class Zero {
- int y;
- int x;
- public Zero(int y, int x) {
- this.y = y;
- this.x = x;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement