463.Island Perimeter

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.

翻译:给出一个二维整数网格形式的地图,其中1表示土地,0表示水。网格单元水平/垂直(不对角线)连接。网格完全被水包围,只有一个岛屿(即一个或多个连接的地面细胞)。岛上没有“湖泊”(水内没有连接到岛上的水)。一个单元格是具有边长为1的正方形。网格为矩形,宽度和高度不超过100.确定岛的周长。

[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
答案:16
说明:周长是16条黄色条纹图片如下:


示例图


public class Solution{
    public int islandPerimeter(int[][] grid){
        if(grid.length == 0 || grid == null)
            return 0;
        int neighbors = 0, int islands = 0;
        for(int i = 0; i < grid.length; i++)
            for(int j = 0; j < grid[i].length; j++){
                if(gird[i][j] == 1){
                    island++;
                    if(i + 1 < grid.length && grid[i+1][j] == 1)
                        neighbors++;
                    if(j + 1 < grid[i].length && grid[i][j+1] == 1)
                        neightbors++;
                }
            }
        return islands * 4 - neighbors * 2;
    }
}
  1. 解决思路:循环遍历数组
  2. 每当走到一个island时,我们只往右和下看,这样能防止重复看neighbor
  3. 每看到一个Neighbor,相当于


    +–+ +–+ +–+–+
    | | + | | -> | |
    +–+ +–+ +–+–+


最后return islands * 4 - neighbor * 2

为什么是Neighbor*2,由上图可知,只要有一个邻居,就会有一个边被两个islands共享,所以要减去这重复就算的2.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值