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.

Example:

[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

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

题目大意:一个二维数组,0代表水域,1代表陆地。有且只有一整块陆地,求陆地的周长。


解题思路:遍历二位数组,对每个格子计算这个格子在整个陆地中的周长是多少。

     如果是0,则代表水域,不用计算周长;

     如果是1,则代表陆地,则分别根据其上下左右的情况计算出这个格子在整个陆地中的周长是多少。

代码如下:(141ms,beats 81.03%)

public class IslandPerimeter {

    //计算每个格子在整个陆地中占据多少周长的函数
    public int getPerimeter(int[][] grid, int x, int y, int width, int height) {
        int perimeter = 0;
        if (grid[y][x] == 0)
            return perimeter;
        if (x == 0)
            perimeter++;
        else {
            if (grid[y][x - 1] == 0)
                perimeter++;
        }
        if (x == width - 1)
            perimeter++;
        else {
            if (grid[y][x + 1] == 0)
                perimeter++;
        }
        if (y == 0)
            perimeter++;
        else {
            if (grid[y - 1][x] == 0)
                perimeter++;
        }
        if (y == height - 1)
            perimeter++;
        else {
            if (grid[y + 1][x] == 0)
                perimeter++;
        }
        return perimeter;
    }

    public int islandPerimeter(int[][] grid) {
        int perimeter = 0;
        int height = grid.length;
        int width = grid[0].length;
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                perimeter += getPerimeter(grid, x, y, width, height);
            }
        }
        return perimeter;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值