```
public class Solution {
public int islandPerimeter(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int sum = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
int count = numOne(grid, i, j);
sum += 4 - count;
}
}
}
return sum;
}
public int numOne(int[][] grid, int i, int j) {
int m = grid.length;
int n = grid[0].length;
int count = 0;
if (i + 1 < m && grid[i + 1][j] == 1) count++;
if (i - 1 >= 0 && grid[i - 1][j] == 1) count++;
if (j - 1 >= 0 && grid[i][j - 1] == 1) count++;
if (j + 1 < n && grid[i][j + 1] == 1) count++;
return count;
}
}
```