LeetCode 463. Island Perimeter

题目描述 LeetCode 463

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:

题目解读

  • 计算小岛的面积,面积示意如上图中的黄色线段

解题思路

  • 遍历数组每一块,如果该块为 1, 则计算它上下左右是否为 0,还要考虑边界,如果上下左右有为 0 的边,或者越界,则小岛面积加 1
  • 示意:
    • 开始遍历,进入第一块,为 0 放弃,进入第二块
    • 进入第 2 块,为 1,则看上下左右; (1) 向上,越界,面积加 1; (2) 向下,下面块为 1,则不是边界; (3) 向左,左面块为 0,则面积加 1; (4) 向右,右面块为 0,面接加
    • 依次遍历...

Code

# include<stdio.h>

int islandPerimeter(int** grid, int gridRowSize, int gridColSize) 
{
    int i, j;
    int sum = 0;

    for(i = 0; i < gridRowSize; i ++)
    {
        for (j = 0; j < gridColSize; j ++)
        {
            if( *(*(grid + i) + j) == 1)
            {
                // up
                if ( i - 1 < 0 || *(*(grid + i - 1) + j) == 0){
                    sum ++;
                }

                // down
                if ( i + 1 == gridRowSize || *(*(grid + i + 1) + j) == 0){
                    sum ++;
                }

                // left
                if ( j - 1 < 0 || *(*(grid + i) + j - 1) == 0){
                    sum ++;
                }

                // right
                if ( j + 1 == gridColSize || *(*(grid + i) + j + 1) == 0){
                    sum ++; 
                }
            }
            else 
            {
                // *(*(grid + i) + j) == 0 
            }
        }
    }

    return sum;
}

int main()
{   
    int i;
    int island[100][100] = {{0,1,0,0},{1,1,1,0},
            {0,1,0,0},{1,1,0,0}};
    int *tmp[100];

    for (i = 0; i < 4; i ++){
        tmp[i] = island[i];
    }

    printf("%d \n", islandPerimeter(tmp,4, 4));
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在南京南站上厕所,一保洁大爷真心乃大神一枚!居然盯着别人撒尿,且不停的说:“对,就是这样,再往前一小步,对,不要洒...
    糗开心阅读 163评论 1 1
  • 年年岁岁、岁岁年年,四季忙着更替交换,岁月像风一般飞扬。春,总在你的盼望中不期而遇。 一天之际在于晨,一年之际在于...
    AL阿林阅读 331评论 4 4
  • 公司:宁波大发化纤有限公司 姓名:冯玉停 期数:六项精进224期感谢二组学员,234期感谢三组志工,260期感谢一...
    尘埃wyzh阅读 152评论 0 0
  • 放得下就不孤独,站的远些就清楚。 你觉得孤独就对了,那是让你认识自己的机会; 你觉得不被理解就对了,那是让你认清朋...
    艳伟阅读 869评论 1 5