美文网首页
#463 Island Perimeter

#463 Island Perimeter

作者: 乐正君Krizma | 来源:发表于2017-04-28 15:25 被阅读0次

    题目:

    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;

    };

    相关文章

      网友评论

          本文标题:#463 Island Perimeter

          本文链接:https://www.haomeiwen.com/subject/kjwnzttx.html