public class Solution {
public int islandPerimeter(int[][] grid) {
//Handle null values
if(grid==null  grid.length<1) return 0;
int rows = grid.length;
int cols = grid[0].length;
int perimeter=0;
/*
* Run through the grid and chekc the boundries of all the positions which have value 1.
* Check the number of '1's surrounding each of the '1's in the grid.
* Every value will have 4 boundries. The number of boundries that contribute
* to the total perimeter is equal to the number of boundries that are not '1'.
* i.e. Contribution ot total perimeter = 4  number of '1's around it.
*/
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(grid[i][j]==1)
{
//Decrement the number of '1's around it.
int boundryCount=4;
if(i<rows1 && grid[i+1][j]==1) boundryCount;
if(i>0 && grid[i1][j]==1) boundryCount;
if(j<cols1 && grid[i][j+1]==1) boundryCount;
if(j>0 && grid[i][j1]==1) boundryCount;
perimeter+=boundryCount;
}
}
}
return perimeter;
}
}
Simple Java Solution with comments


similar
public class Solution { public int islandPerimeter(int[][] grid) { if(grid == null) return 0; int row = grid.length; int col = grid[0].length; int count=0, num=0; for(int i = 0; i < row; i++) for(int j = 0; j < col; j++){ if(grid[i][j] == 1){ num++; if( (i1>=0) && grid[i1][j] == 1) count++; //up if( (i+1<row) && grid[i+1][j] == 1) count++; //down if( (j1>=0) && grid[i][j1] == 1) count++; //left if( (j+1<col) && grid[i][j+1] == 1) count++; //right } } return (num*4count); } }