leetcode 463. Island Perimeter

本文介绍了一种计算二维网格中岛屿周长的方法。网格由0和1组成,1代表陆地,0代表水域。通过遍历网格,对于每个陆地单元格,初始计数为4,然后检查其四周是否有相邻的陆地,若有则减1,最终得到的总和即为岛屿的周长。

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:

Input:
[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

Output: 16

Explanation: The perimeter is the 16 yellow stripes in the image below:

题目大意:求陆地的周长

思路一:一个land四个边,四个方向每有一个相邻的land,边少一。

 1 int islandPerimeter(vector<vector<int>>& grid) {
 2         int cnt = 0;
 3         int m = grid.size();
 4         if (m == 0)
 5             return 0;
 6         int n = grid[0].size();
 7         int dx[4] = {-1, 0, 1, 0};
 8         int dy[4] = {0, 1, 0, -1};
 9         for (int i = 0; i < m; ++i) {
10             for (int j = 0; j < n; ++j) {
11                 if (grid[i][j] == 1) {
12                     cnt += 4;
13                     for (int k = 0; k < 4; ++k) {
14                         int newx = i + dx[k];
15                         int newy = j + dy[k];
16                         if (newx >= 0 && newx < m && newy >= 0 && newy < n && grid[newx][newy] == 1) {
17                             --cnt;
18                         }
19                     }
20                 }
21             }
22         }
23         return cnt;
24     }

问题:每个是1的land大概访问了4次。

 

思路二:

转载于:https://www.cnblogs.com/qinduanyinghua/p/11551358.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值