# Simple JavaScript O(n^2) solution

• If the cell is island, calculate it's surrounding neighbor.

If it's top neighbor is an island, the perimeter should minus 1

``````/**
* @param {number[][]} grid
* @return {number}
*/
var islandPerimeter = function(grid) {
if (!grid || grid.length <= 0) {
return 0;
}
var perimeter = 0;
var colMax = grid[0].length;
var rowMax = grid.length;
for (var i = 0; i < rowMax; i++) {
for (var j = 0; j < colMax; j++) {
var item = grid[i][j];
if (item === 0) {
continue;
} else if (item === 1) {
var total = 4;
// top
if (hasCell(i - 1, j, grid)) {
total--;
}
// left
if (hasCell(i, j - 1, grid)) {
total--;
}
// bottom
if (hasCell(i + 1, j, grid)) {
total--;
}
// right
if (hasCell(i, j + 1, grid)) {
total--;
}

perimeter += total;
}
}
}
return perimeter;
};

function hasCell(row, col, grid) {
if (row >= 0 && col >= 0 && row < grid.length && col < grid[0].length) {
if (grid[row][col] === 1) {
return true;
}
}
return false;
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.