zoukankan      html  css  js  c++  java
  • 【LeetCode】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.

    [[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组成一个岛,求岛的周长

    解题思路:

      感觉和419. Battleships in a Board这个题很像,遍历整个数组,考虑每个值上面和左边的值是否为1,是否相接

       周长=块数*4-相接个数*2

     1 int islandPerimeter(int** grid, int gridRowSize, int gridColSize) {
     2     int i,j;
     3     int count=0,ad=0;
     4     for(i=0;i<gridRowSize;i++)
     5     {
     6         for(j=0;j<gridColSize;j++)
     7         {
     8             if(grid[i][j])
     9             {
    10                 count++;
    11             if(0==i&&j>0)
    12                { 
    13                    if(grid[i][j-1])
    14                     ad++;
    15                    
    16                }
    17             else
    18                 if(i!=0&&0==j)
    19                    {
    20                        if(grid[i-1][j])
    21                         ad++;
    22                    }
    23                 else 
    24                     if(i!=0&&j>0)
    25                     {
    26                         if(grid[i][j-1])
    27                             ad++;
    28                         if(grid[i-1][j])
    29                             ad++;
    30                     }
    31             }
    32         }
    33     }
    34     return 4*count-2*ad;
    35 }
  • 相关阅读:
    2015多校1006.First One
    2015多校.MZL's endless loop(欧拉回路的机智应用 || 构造)
    LUXURY 8
    矩阵快速幂模板
    博弈入门
    cf558c(bfs)
    LUXURY 7
    dfs序 + RMQ = LCA
    双端队列
    UVa-401 Palindromes
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6149108.html
Copyright © 2011-2022 走看看