Skip to content

Commit cda2990

Browse files
committed
LeetCode #827: Making A Large Island
1 parent 17861cc commit cda2990

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

LeetCode/827/Solution.java

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/*
2+
* Author: Minho Kim (ISKU)
3+
* Date: November 14, 2019
4+
* E-mail: minho.kim093@gmail.com
5+
*
6+
* https://github.com/ISKU/Algorithm
7+
* https://leetcode.com/problems/making-a-large-island/
8+
*/
9+
10+
class Solution {
11+
12+
private final int[] dy = { 1, -1, 0, 0 };
13+
private final int[] dx = { 0, 0, 1, -1 };
14+
15+
private int[][] map;
16+
private boolean[][] visited;
17+
18+
private Map<Point, Integer> groupMap;
19+
private int[] count;
20+
private int Y, X, answer;
21+
22+
public int largestIsland(int[][] grid) {
23+
map = grid;
24+
Y = map.length;
25+
X = map[0].length;
26+
groupMap = new HashMap<>();
27+
28+
int groupNumber = 0;
29+
count = new int[2500];
30+
visited = new boolean[Y][X];
31+
for (int y = 0; y < Y; y++)
32+
for (int x = 0; x < X; x++)
33+
if (!visited[y][x] && map[y][x] == 1)
34+
dfs(y, x, groupNumber++);
35+
36+
for (int y = 0; y < Y; y++) {
37+
for (int x = 0; x < X; x++) {
38+
if (map[y][x] == 1)
39+
continue;
40+
41+
Set<Integer> set = new HashSet<>();
42+
for (int i = 0; i < 4; i++) {
43+
int ny = y + dy[i];
44+
int nx = x + dx[i];
45+
if (ny < 0 || ny >= Y || nx < 0 || nx >= X || map[ny][nx] == 0)
46+
continue;
47+
48+
Point p = new Point(ny, nx);
49+
int group = groupMap.get(p);
50+
set.add(group);
51+
}
52+
53+
int sum = 0;
54+
if (!set.isEmpty())
55+
for (int group : set)
56+
sum += count[group];
57+
58+
answer = Math.max(answer, sum + 1);
59+
}
60+
}
61+
62+
return answer;
63+
}
64+
65+
private void dfs(int y, int x, int group) {
66+
visited[y][x] = true;
67+
groupMap.put(new Point(y, x), group);
68+
count[group]++;
69+
answer = Math.max(answer, count[group]);
70+
71+
for (int i = 0; i < 4; i++) {
72+
int ny = y + dy[i];
73+
int nx = x + dx[i];
74+
if (ny < 0 || ny >= Y || nx < 0 || nx >= X || visited[ny][nx] || map[ny][nx] == 0)
75+
continue;
76+
77+
dfs(ny, nx, group);
78+
}
79+
}
80+
81+
private class Point {
82+
public int y, x;
83+
84+
public Point(int y, int x) {
85+
this.y = y;
86+
this.x = x;
87+
}
88+
89+
@Override
90+
public int hashCode() {
91+
return y * 2500 + x;
92+
}
93+
94+
@Override
95+
public boolean equals(Object o) {
96+
Point p = (Point) o;
97+
if (this.y == p.y && this.x == p.x)
98+
return true;
99+
return false;
100+
}
101+
}
102+
}

0 commit comments

Comments
 (0)