LeetCode463 Island Perimeter

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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
2
3
4
5
6
[[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:
Explanation

思路

给一个地图,含有水和陆地,陆地为一个联通块(四方向联通,且联通块内部不会包含水),问联通块的周长。

首先一块陆地(1*1大小)对周长的贡献是4,只有当它在某个方向上的邻居也是陆地时,这个贡献被抵消掉。因此只要遍历每块陆地的4个方向,判断一下是否有贡献即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int r = grid.size(), c = grid[0].size();
int perimeter = 0;
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // 四个方向
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
if (grid[i][j] == 1) {
for (int k = 0; k < 4; ++k) {
int x = i + dir[k][0], y = j + dir[k][1]; // 邻居坐标
// 若越界 或者 是水 ,则加上该方向上的贡献
if (x < 0 || x >= r || y < 0 || y >= c || grid[x][y] == 0) {
perimeter++;
}
}
}
}
}
return perimeter;
}
};
分享到 评论