[463]Island Perimeter

leetcode

first version

First version is straight forward, check each unit, and check the four units around it. If they are valid island, continue. else, perimeter increment.

public class Solution {
    int[][] grid;
    int row;
    int col;

    public int islandPerimeter(int[][] grid) {
        this.grid = grid;
        row = grid.length;
        if(row == 0)return 0;
        col = grid[0].length;

        int perimeter = 0;
        for(int i = 0; i < row; i ++){
            for(int j = 0; j < col; j++){
                if(!isIsland(i,j))continue;
                if(!isIsland(i - 1, j))perimeter++;
                if(!isIsland(i + 1, j))perimeter++;
                if(!isIsland(i, j - 1))perimeter++;
                if(!isIsland(i, j + 1))perimeter++;
            }
        }
        return perimeter;

    }

    public boolean isIsland(int i, int j){
        if(i < 0 || i >= row || j < 0 || j >= col)return false;
        return grid[i][j] == 1;
    }


}

Other versions

I see some top solutions on leetcode discussion, and the idea is the same. some optimization is to count 4 for each unit, and when it has a neighbors( right and down directions to avoid repeat), then minus 2, since the two neighbors will share an edge.

see this solution

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,588评论 0 23
  • 嗯,太多啦
    泽阳9阅读 1,391评论 1 0
  • 打开朋友圈 在我长针眼之前 失眠过n次 在晨光熹微 浑浑噩噩以为自己终将睡去前 鬼使神差的看到了一些东西 天生贱气...
    贫困漂亮女大学生阅读 1,585评论 0 0
  • 提到柬埔寨,很多人的第一印象应该就是“贫穷”的第三世界国家。但是今天Vidu想说说自己眼中看到的不同的柬埔寨。 V...
    粤旅拍阅读 4,272评论 0 0
  • 价值观需要不断打磨,才能帮助自己改变命运,掌握命运。想起很多人一辈子也没有对价值观进行过深入打磨,就一辈子都陷入无...
    卡诺09阅读 2,920评论 0 0

友情链接更多精彩内容