Island Perimeter 题解

来源:互联网 发布:java gc日志 编辑:程序博客网 时间:2024/05/16 09:38

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.


链接:点击打开链接


题解:

由题意可知,我们需要求出 “陆地” 的外围长度。首先,我们对矩阵按照从左到右,从上到下的搜索策略进行遍历,当发现该块的值为“1”时,表示陆地,我们记录该块,如果发现有两个相连的“陆地”时,我们同样需要记录。我们用

if(i!=0 && grid[i-1][j]==1)    del++;if(j!=0 && grid[i][j-1]==1)    del++;

这段代码实现。按照数学上的理论方法,一个块周长为4,如果存在两个块相连接,则会存在边的“抵消”,会使它们拼接的图形周长减少(如:两个周长为4的正方形,连接后周长为4*2-2)。因此,最后“陆地”的外围长度为:(陆地块数量*4) 减去 (重复的陆地块数量*2)。算法复杂度为 O(n²)。

代码:

class Solution {public:    int islandPerimeter(vector<vector<int>>& grid) {        int ans=0;         int del=0;        for(int i=0; i<grid.size(); i++){            for(int j=0;j<grid[i].size(); j++){                if(grid[i][j]==1){                   ans++;                   if(i!=0 && grid[i-1][j]==1){                       del++;                   }                   if(j!=0 && grid[i][j-1]==1){                       del++;                   }                }            }        }   return ans*4-del*2;    }};

0 0
原创粉丝点击