Leetcode 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.

 [[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]
island.png

Answer: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:

最直接的解法:

int islandPerimeter(vector<vector<int>>& grid) {
    int count = 0;
    if(grid.empty()){
        return count;
    }
    for(int i = 0;i < grid.size();i++){
        for(int j = 0;j < grid[0].size();j++){
            if(grid[i][j] == 1){
                if( (i == 0) || (i - 1 >= 0 && grid[i - 1][j] == 0) )
                    count ++;
                if( (i == grid.size() - 1) || (i + 1 < grid.size() && grid[i + 1][j] == 0))
                    count ++;
                if( (j == 0) || (j - 1 >= 0 && grid[i][j - 1] == 0) )
                    count ++;
                if( (j == grid[0].size() - 1) || (j + 1 < grid[0].size() && grid[i][j + 1] == 0))
                    count ++;
            }        
        }
    }
    return count;
}

其实可以有更简单的解法的:

int islandPerimeter(vector<vector<int>>& grid) {
    int count=0, repeat=0;
    for(int i=0;i<grid.size();i++)
    {
        for(int j=0; j<grid[i].size();j++)
            {
                if(grid[i][j]==1)
                {
                    count ++;
                    if(i!=0 && grid[i-1][j] == 1) repeat++;
                    if(j!=0 && grid[i][j-1] == 1) repeat++;
                }
            }
    }
    return 4*count-repeat*2;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,789评论 0 33
  • 题目 You are given a map in form of a two-dimensional integ...
    Eazow阅读 377评论 0 0
  • 梧桐叶上三更雨,叶叶声声是别离。霜染秋色浓,客行欲语休。弱水替沧海,叙酒话愁肠。
    卜比阅读 149评论 0 2
  • “色狼!你个色狼!” “啪!”的一声,强子的脸被美女扇了一巴掌。 “我不是色狼。”强子不服气地说。 “那你干嘛老紧...
    詹妮儿阅读 1,200评论 8 7
  • iOS面试必考问题 1、多态、继承、封装 封装:就是对类中的一些字段,方法进行保护,不被外界所访问到,有一种权限的...
    zero_zql阅读 514评论 0 3