leetcode 463. Island Perimeter

来源:互联网 发布:豚丫丫这款软件好吗 编辑:程序博客网 时间:2024/06/14 23:11

原题:

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: 16Explanation: The perimeter is the 16 yellow stripes in the image below:
求岛屿周长。岛屿没有内陆刀。

代码如下:

int islandPerimeter(int** grid, int gridRowSize, int gridColSize) {    int result=0;    int flag=0;    printf("%d,%d",gridRowSize,gridColSize);    for(int n=0;n<gridRowSize;n++)    {        for(int m=0;m<gridColSize;m++)        {            if(*(*(grid+n)+m)==1)            {                if(n!=0&&*(*(grid+n-1)+m)==1)                    flag++;                if(m!=0&&*(*(grid+n)+m-1)==1)                    flag++;                result=result+4;            }        }    }    return result-flag*2;}
得出交叉周长就好,然后拿总的周长去减一下就搞定。