#463 Island Perimeter

題目:

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;

};

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容