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:

leetcode 463. Island Perimeter

题目大意:求陆地的周长

思路一:一个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次。

 

思路二:

上一篇:使用WCF的Trace与Message Log功能


下一篇:Photoshop调色实例教程:加强色彩的对比