您好,欢迎来到哗拓教育。
搜索
您的当前位置:首页leetcode 463. Island Perimeter

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo2.com 版权所有 湘ICP备2023021991号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务