Java
public class Solution {
public int islandPerimeter(int[][] grid) {
int count=0;
for(int i=0;i<grid.length;i++)
{
for(int j=0;j<grid[i].length;j++)
{
if(grid[i][j]==1)
{
int tmp=4;
if(i>=1&&grid[i-1][j]==1)
tmp--;
if(i<grid.length-1&&grid[i+1][j]==1)
tmp--;
if(j>=1&&grid[i][j-1]==1)
tmp--;
if(j<grid[i].length-1&&grid[i][j+1]==1)
tmp--;
count+=tmp;
}
}
}
return count;
}
}
Javascript
/**
* @param {number[][]} grid
* @return {number}
*/
var islandPerimeter = function(grid) {
var count=0;
for(var i=0;i<grid.length;i++)
{
for(var j=0;j<grid[i].length;j++)
{
if(grid[i][j]==1)
{
var tmp=4;
if(i>=1&&grid[i-1][j]==1)
tmp--;
if(i<grid.length-1&&grid[i+1][j]==1)
tmp--;
if(j>=1&&grid[i][j-1]==1)
tmp--;
if(j<grid[i].length-1&&grid[i][j+1]==1)
tmp--;
count+=tmp;
}
}
}
return count;
};
优解,思路差不多,想法要好一点