-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.java
58 lines (42 loc) · 1.49 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
import java.awt.Point;
import java.util.Stack;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Solution {
private static void flood(int i, int j, int[][] map) {
Stack<Point> neighbours = new Stack<>();
neighbours.push(new Point(i, j));
while (!neighbours.isEmpty()) {
Point p = neighbours.pop();
int x = (int) p.getX();
int y = (int) p.getY();
if (x < 0 || y < 0 || x >= map.length || y >= map[x].length)
continue;
if (map[x][y] != 1)
continue;
map[x][y] = -1;
neighbours.push(new Point(x - 1, y));
neighbours.push(new Point(x + 1, y));
neighbours.push(new Point(x, y - 1));
neighbours.push(new Point(x, y + 1));
}
}
public static int solve(int[][] map) {
int islandCount = 0;
for (int i = 0; i < map.length; i++) {
int[] row = map[i];
for (int j = 0; j < row.length; j++) {
if (map[i][j] == -1 || map[i][j] == 0)
continue;
islandCount++;
flood(i, j, map);
}
}
return islandCount;
}
public static void main(String[] args) {
int[][] map = { { 1, 0, 0, 0, 0, }, { 0, 0, 1, 1, 0 }, { 0, 1, 1, 0, 0 }, { 0, 0, 0, 0, 0 }, { 1, 1, 0, 0, 1 },
{ 1, 1, 0, 0, 1 } };
System.out.println(solve(map)); // 4
}
}