```
public int islandPerimeter(int[][] grid) {
int r = grid.length;
int c = grid[0].length;
int p = 0;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (grid[i][j] == 1) {
p += perimeter(i == 0 ? -1 : grid[i - 1][j], i == r - 1 ? -1 : grid[i + 1][j], j == 0 ? -1 : grid[i][j - 1], j == c - 1 ? -1 : grid[i][j + 1]);
}
}
}
return p;
}
//Get cell perimeter. Add 1 if its neighbor not a land.
private int perimeter(int up, int down, int left, int right) {
return (up == 1 ? 0 : 1) + (down == 1 ? 0 : 1) + (left == 1 ? 0 : 1) + (right == 1 ? 0 : 1);
}
```