forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
61 lines (48 loc) · 1.63 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
61
/**
* @author Oleg Cherednik
* @since 09.02.2019
*/
public class Solution {
public static void main(String... args) {
int[][] matrix = {
{ 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(findIslandsAmount(matrix));
}
public static int findIslandsAmount(int[][] matrix) {
int[][] visited = copyMatrix(matrix);
int id = 1;
for (int row = 0; row < matrix.length; row++)
for (int col = 0; col < matrix[row].length; col++)
if (dfs(visited, row, col, id))
id++;
return id - 1;
}
private static boolean dfs(int[][] visited, int row, int col, int id) {
if (row < 0 || row >= visited.length)
return false;
if (col < 0 || col >= visited[row].length)
return false;
if (visited[row][col] != -1)
return false;
visited[row][col] = id;
dfs(visited, row, col + 1, id);
dfs(visited, row, col - 1, id);
dfs(visited, row + 1, col, id);
dfs(visited, row - 1, col, id);
return true;
}
private static int[][] copyMatrix(int[][] matrix) {
int[][] res = new int[matrix.length][];
for (int row = 0; row < matrix.length; row++) {
res[row] = new int[matrix[row].length];
for (int col = 0; col < matrix[row].length; col++)
res[row][col] = matrix[row][col] != 0 ? -1 : 0;
}
return res;
}
}