-
Notifications
You must be signed in to change notification settings - Fork 16
/
NumberOfIslands.java
52 lines (43 loc) · 1.51 KB
/
NumberOfIslands.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
// https://leetcode.com/problems/number-of-islands
// T: O(m * n)
// T: O(m * n)
public class NumberOfIslands {
private static final char VISITED = '0';
private static final char ISLAND = '1';
public int numIslands(char[][] grid) {
final int rows = grid.length, columns = grid[0].length;
int islands = 0;
for (int row = 0 ; row < rows ; row++) {
for (int column = 0 ; column < columns ; column++) {
if (isIsland(grid[row][column])) {
islands++;
markIslandAsSeen(grid, row, column);
}
}
}
return islands;
}
private boolean isIsland(char c) {
return c == ISLAND;
}
private void markIslandAsSeen(char[][] grid, int row, int column) {
if (!isValidPosition(grid, row, column) || !isIsland(grid[row][column])) return;
markVisited(grid, row, column);
markIslandAsSeen(grid, row - 1, column);
markIslandAsSeen(grid, row, column + 1);
markIslandAsSeen(grid, row + 1, column);
markIslandAsSeen(grid, row, column - 1);
}
private boolean isValidPosition(char[][] grid, int row, int column) {
return row >= 0
&& row < grid.length
&& column >= 0
&& column < grid[0].length;
}
private boolean alreadyVisited(char c) {
return c == VISITED;
}
private void markVisited(char[][] grid, int row, int column) {
grid[row][column] = VISITED;
}
}