```
public int islandPerimeter(int[][] grid) {
int m = grid.length, n = grid[0].length;
int result = 0;
// add 4 for each land
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
result += 4;
//check if any of four direction is connected, minus 1 each time.
if (i - 1 >= 0 && grid[i - 1][j] == 1) result--;
if (i + 1 < m && grid[i + 1][j] == 1) result--;
if (j - 1 >= 0 && grid[i][j - 1] == 1) result--;
if (j + 1 < n && grid[i][j + 1] == 1) result--;
}
}
}
return result;
}
```