首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode463. Island Perimeter

leetcode463. Island Perimeter

作者头像
眯眯眼的猫头鹰
发布2019-08-13 11:06:10
3120
发布2019-08-13 11:06:10
举报

题目要求

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:

Input:
[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

Output: 16

Explanation: The perimeter is the 16 yellow stripes in the image below:
clipboard.png
clipboard.png

用一个二维数组来表示一块岛屿的土地情况,其中1代表土地,0代表海洋。要求计算出岛屿的周长。题目中特别强调了不存在内陆湖的存在,其实是变相的降低了题目的难度。即我们只要看到1和0相邻,就可以判断出到了岛的边缘。

思路和代码

这题不难,直观的来看,其实只要判断出这一块土地几面临海就知道需要加上几条边长。临海的判断有两个,一个是这块地位于数组的边缘,一个是这块地相邻的元素为0,即海洋。遇到这种情况我们就需要将边界领土加一即可。代码如下:

    public int islandPerimeter(int[][] grid) {
        int perimeter = 0;
        for(int i = 0 ; i<grid.length ; i++) {
            for(int j = 0 ; j<grid[i].length ; j++) {
                int num = grid[i][j];
                if(num == 1) {
                    //上方临海
                    if(i == 0 || grid[i-1][j]==0) perimeter++;
                    //左侧临海
                    if(j == 0 || grid[i][j-1]==0) perimeter++;
                    //右侧临海
                    if(i == grid.length-1 || grid[i+1][j]==0) perimeter++;
                    //下方临海
                    if(j == grid[i].length-1 || grid[i][j+1]==0) perimeter++;
                }
            }
        }
        return perimeter;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档