-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
60 lines (54 loc) · 2.76 KB
/
Solution.java
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
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int maxArea = 0;
Map<String, Integer> dfsMap = new HashMap<String, Integer>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1 && dfsMap.get(String.valueOf(i) + "X" + String.valueOf(j)) == null) {
int area = 0;
List<Map<String, Integer>> stack = new ArrayList<Map<String, Integer>>();
Map<String, Integer> origin = new HashMap<String, Integer>();
origin.put("x", j);
origin.put("y", i);
stack.add(origin);
while (stack.size() > 0) {
Map<String, Integer> point = stack.get(stack.size() - 1);
stack.remove(stack.size() - 1);
int x = point.get("x"),
y = point.get("y");
if (dfsMap.get(String.valueOf(y) + "X" + String.valueOf(x)) == null) {
area++;
dfsMap.put(String.valueOf(y) + "X" + String.valueOf(x), 1);
if (y >= 1 && grid[y - 1][x] == 1) {
point = new HashMap<String, Integer>();
point.put("x", x);
point.put("y", y - 1);
stack.add(point);
}
if (y + 1 < grid.length && grid[y + 1][x] == 1) {
point = new HashMap<String, Integer>();
point.put("x", x);
point.put("y", y + 1);
stack.add(point);
}
if (x >= 1 && grid[y][x - 1] == 1) {
point = new HashMap<String, Integer>();
point.put("x", x - 1);
point.put("y", y);
stack.add(point);
}
if (x + 1 < grid[0].length && grid[y][x + 1] == 1) {
point = new HashMap<String, Integer>();
point.put("x", x + 1);
point.put("y", y);
stack.add(point);
}
}
}
maxArea = Math.max(maxArea, area);
}
}
}
return maxArea;
}
}