问题来源:
问题描述:
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:
我的解决方案:
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int row=grid.size();
int column=grid[0].size();
int ret=0;
if(!row && !column)//空
return 0;
for(int i=0;i<row;++i)
{
for(int j=0;j<column;++j)
{
if(grid[i][j]==0)
continue;
if(i==0)
ret++;
if(i==row-1)
ret++;
if(j==0)
ret++;
if(j==column)
ret++;
if(j==column-1)
ret++;
if(i>0 && grid[i-1][j]==0)
ret++;
if(i<row-1 && grid[i+1][j]==0)
ret++;
if(j>0 && grid[i][j-1]==0)
ret++;
if(j<column-1 && grid[i][j+1]==0)
ret++;
}
}
return ret;
}
};
思考:
用的方法挺笨的,暴力遍历整个二维数组,看每个1元素的上下左右是否有0,如果是0或者边界则周长加上1个边,最开始行和列也弄反了,浪费了蛮多时间,后来想一下可以拆分成行方向和列方向,每有一个1,则周长加4,然后减去重复的部分,在行上每有一个重复的则减2,在列上也一样.代码如下:(来源beckswu)
int islandPerimeter(vector<vector<int>>& grid) {
int count=0, repeat=0;
for(int i=0;i<grid.size();i++)
{
for(int j=0; j<grid[i].size();j++)
{
if(grid[i][j]==1)
{
count ++;
if(i!=0 && grid[i-1][j] == 1) repeat++;
if(j!=0 && grid[i][j-1] == 1) repeat++;
}
}
}
return 4*count-repeat*2;
}
博客探讨了一个关于二维数组中求解岛屿周长的问题,其中1表示陆地,0表示水。问题要求计算完全被水包围且无湖泊的唯一岛屿的周长。博主采用暴力遍历方法,对每个陆地单元格检查相邻单元格,遇到水或边界时增加周长计数,最终优化代码以避免重复计算。

5580

被折叠的 条评论
为什么被折叠?



