#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

grid[len][j] = 0;

}

for(let i=0;i

let tmp = 0;

grid[i][wid] = 0;

for(let j=0;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

let tmp = 0;

for(let i=0;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;

};

你可能感兴趣的:(#463 Island Perimeter)