博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Island Perimeter 岛屿周长
阅读量:6974 次
发布时间:2019-06-27

本文共 2175 字,大约阅读时间需要 7 分钟。

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:

这道题给了我们一个格子图,若干连在一起的格子形成了一个小岛,规定了图中只有一个相连的岛,且岛中没有湖,让我们求岛的周长。我们知道一个格子有四条边,但是当两个格子相邻,周围为6,若某个格子四周都有格子,那么这个格子一条边都不算在周长里。那么我们怎么统计出岛的周长呢?第一种方法,我们对于每个格子的四条边分别来处理,首先看左边的边,只有当左边的边处于第一个位置或者当前格子的左面没有岛格子的时候,左边的边计入周长。其他三条边的分析情况都跟左边的边相似,这里就不多叙述了,参见代码如下:

解法一:

class Solution {public:    int islandPerimeter(vector
>& grid) { if (grid.empty() || grid[0].empty()) return 0; int m = grid.size(), n = grid[0].size(), res = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == 0) continue; if (j == 0 || grid[i][j - 1] == 0) ++res; if (i == 0 || grid[i - 1][j] == 0) ++res; if (j == n - 1 || grid[i][j + 1] == 0) ++res; if (i == m - 1 || grid[i + 1][j] == 0) ++res; } } return res; }};

下面这种方法对于每个岛屿格子先默认加上四条边,然后检查其左面和上面是否有岛屿格子,有的话分别减去两条边,这样也能得到正确的结果,参见代码如下:

解法二:

class Solution {public:    int islandPerimeter(vector
>& grid) { if (grid.empty() || grid[0].empty()) return 0; int res = 0, m = grid.size(), n = grid[0].size(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == 0) continue; res += 4; if (i > 0 && grid[i - 1][j] == 1) res -= 2; if (j > 0 && grid[i][j - 1] == 1) res -= 2; } } return res; }};

本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。

你可能感兴趣的文章
“一票易得” 微微网络电话五一抢票进行时
查看>>
MySQL使用可重复读作为默认隔离级别的原因
查看>>
【工具使用系列】关于 MATLAB 径向基神经网络,你需要知道的事
查看>>
让我们一起Go(十一)
查看>>
关于USB数据存储这一块的技术问题
查看>>
创建第一个Azure Liunx虚拟机
查看>>
unstrict模式
查看>>
提高red5性能几个配置。
查看>>
tab键技巧小结
查看>>
我的友情链接
查看>>
数据库管理中文件的使用
查看>>
WPF获取应用程序路径方法,获取程序运行路径方法
查看>>
计算机英语单词汇总
查看>>
Scala 学习
查看>>
linux系统日志
查看>>
play框架之环境搭建
查看>>
小编带着小白看springboot源码5
查看>>
jquery 的使用
查看>>
如何合并多个PDF文件
查看>>
16.磁盘组成的冗余阵列《Mr.Robot》
查看>>