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 }
  • 相关阅读:
    两个有序链表的合并
    Perl学习笔记
    生信-基本概念
    生信-序列比较dp[未完成]
    PAT 1091 Acute Stroke [难][bfs]
    PAT 1038 Recover the Smallest Number[dp][难]
    PAT 1078 Hashing[一般][二次探查法]
    PAT 1122 Hamiltonian Cycle[比较一般]
    PAT 1151 LCA in a Binary Tree[难][二叉树]
    PAT 1148 Werewolf
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6149108.html
Copyright © 2011-2022 走看看