-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Loading status checks…
Time: 68 ms (92.58%), Space: 71.2 MB (93.99%) - LeetHub
1 parent
74d1250
commit 40716a6
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
65 changes: 65 additions & 0 deletions
65
0827-making-a-large-island/0827-making-a-large-island.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
class Solution { | ||
private int n; | ||
private int grid[][]; | ||
private Map<Integer, Integer> map = new HashMap<>(); | ||
private static final int directions[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; | ||
|
||
public int largestIsland(int[][] grid) { | ||
this.n = grid.length; | ||
this.grid = grid; | ||
int color = 2; | ||
int area = 0; | ||
boolean hasZero = false; | ||
|
||
for (int i = 0; i < n; i++) { | ||
for (int j = 0; j < n; j++) { | ||
if (grid[i][j] == 1) { | ||
int size = dfs(i, j, color); | ||
map.put(color, size); | ||
area = Math.max(area, size); | ||
color++; | ||
} | ||
else hasZero = true; | ||
} | ||
} | ||
|
||
if (!hasZero) return area; | ||
|
||
for (int i = 0; i < n; i++) { | ||
for (int j = 0; j < n; j++) { | ||
if (grid[i][j] == 0) { | ||
Set<Integer> set = new HashSet<>(); | ||
int curr = 1; | ||
|
||
for (int dir[] : directions) { | ||
int x = i + dir[0], y = j + dir[1]; | ||
if (isValid(x, y) && grid[x][y] > 1 && set.add(grid[x][y])) { | ||
curr += map.get(grid[x][y]); | ||
} | ||
} | ||
|
||
area = Math.max(area, curr); | ||
} | ||
} | ||
} | ||
|
||
return area; | ||
} | ||
|
||
private int dfs(int i, int j, int color) { | ||
if (!isValid(i, j) || grid[i][j] != 1) return 0; | ||
|
||
grid[i][j] = color; | ||
int size = 1; | ||
|
||
for (int dir[] : directions) { | ||
size += dfs(i + dir[0], j + dir[1], color); | ||
} | ||
|
||
return size; | ||
} | ||
|
||
private boolean isValid(int i, int j) { | ||
return i >= 0 && i < n && j >= 0 && j < n; | ||
} | ||
} |