#463 Island Perimeter

2017-04-28  本文已影响0人  乐正君Krizma

题目:

You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.


代码:

var islandPerimeter = function(grid) {    

var total = 0, gap = 0;    

let len = grid.length;    

let wid = grid[0].length;    

grid[len] = [];    

for(let j=0;j<wid+1;++j){

grid[len][j] = 0;

}

for(let i=0;i<len+1;++i){

let tmp = 0;

grid[i][wid] = 0;

for(let j=0;j<wid+1;++j){

total+=grid[i][j];

if(tmp!==tmp+grid[i][j]){

tmp+=grid[i][j];

} else if (tmp>0) {         

gap += tmp-1;                

tmp = 0;            

}        

}    

}    

for(let j=0;j<wid+1;++j){

let tmp = 0;

for(let i=0;i<len+1;++i){

if(tmp!==tmp+grid[i][j]){

tmp+=grid[i][j];

} else if (tmp>0) {

gap+=tmp-1;

tmp=0;

}

}

}

return total*4 - gap*2;

};

上一篇下一篇

猜你喜欢

热点阅读