leetcode 463. Island Perimeter - Go语言中文社区

leetcode 463. 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.

 

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

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_30918415/article/details/102452126
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-05-16 17:09:26
  • 阅读 ( 1139 )
  • 分类:算法

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢