美文网首页
[463]Island Perimeter

[463]Island Perimeter

作者: 秋_轩 | 来源:发表于2016-12-25 06:19 被阅读0次

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

相关文章

网友评论

      本文标题:[463]Island Perimeter

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