similar solution:

public class Solution {
public int islandPerimeter(int[][] grid) {
int perimeter=0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(!isValid(grid,i,j)) continue;
if(!isValid(grid,i-1,j)) perimeter++; //left
if(!isValid(grid,i+1,j)) perimeter++; //right
if(!isValid(grid,i,j-1)) perimeter++; //top
if(!isValid(grid,i,j+1)) perimeter++; //bottom
}
}
return perimeter;
}
private boolean isValid(int[][] grid, int p,int q){
if(p<0||p>=grid.length||q<0||q>=grid[0].length||grid[p][q]==0) return false;
return true;
}
}