-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIslandPerimeter.java
91 lines (84 loc) · 3.22 KB
/
IslandPerimeter.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package solutions;
// [Problem] https://leetcode.com/problems/island-perimeter
class IslandPerimeter {
// Matrix simple counting
// O(mn) time, where m = row length, n = column length
// O(1) space
public int islandPerimeter(int[][] grid) {
int rowLength = grid.length, colLength = grid[0].length;
int perimeter = 0;
for (int row = 0; row < rowLength; row++) {
for (int col = 0; col < colLength; col++) {
if (grid[row][col] == 1) {
if (row == 0 || grid[row - 1][col] == 0) { // top
perimeter++;
}
if (row == rowLength - 1 || grid[row + 1][col] == 0) { // bottom
perimeter++;
}
if (col == 0 || grid[row][col - 1] == 0) { // left
perimeter++;
}
if (col == colLength - 1 || grid[row][col + 1] == 0) { // right
perimeter++;
}
}
}
}
return perimeter;
}
// Matrix neighbor counting
// O(mn) time, O(1) space
public int islandPerimeterNeighborCounting(int[][] grid) {
int rowLength = grid.length, colLength = grid[0].length;
int islands = 0, neighbors = 0;
for (int row = 0; row < rowLength; row++) {
for (int col = 0; col < colLength; col++) {
if (grid[row][col] == 1) {
islands++;
if (row < rowLength - 1 && grid[row + 1][col] == 1) {
neighbors++; // right neighbor
}
if (col < colLength - 1 && grid[row][col + 1] == 1) {
neighbors++; // bottom neighbor
}
}
}
}
return islands * 4 - neighbors * 2;
}
// DFS
// O(mn) time, O(1) space
public int islandPerimeterDfs(int[][] grid) {
int rowLength = grid.length, colLength = grid[0].length;
for (int row = 0; row < rowLength; row++) {
for (int col = 0; col < colLength; col++) {
if (grid[row][col] == 1) {
return getPerimeter(grid, row, col);
}
}
}
return 0;
}
private int getPerimeter(int[][] grid, int row, int col) {
if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] == 0) {
return 1;
}
if (grid[row][col] == -1) { // has been visited
return 0;
}
grid[row][col] = -1;
return getPerimeter(grid, row - 1, col) // top
+ getPerimeter(grid, row + 1, col) // bottom
+ getPerimeter(grid, row, col - 1) // left
+ getPerimeter(grid, row, col + 1); // right
}
// Test
public static void main(String[] args) {
IslandPerimeter solution = new IslandPerimeter();
int[][] input = {{0, 1, 0, 0}, {1, 1, 1, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}};
int expectedOutput = 16;
int actualOutput = solution.islandPerimeter(input);
System.out.println("Test passed? " + (expectedOutput == actualOutput));
}
}