LeetCode-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:

[[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:


翻译:

你被给定一块由一个二维网格表示的地图,其中1代表陆地,0代表水。网格的单元格水平/垂直连接(不是对角线)。网格整体被水包围,并且只有一个岛(即,一个或多个陆地单元格相连)。岛里不包含"湖"(里面的水没有连接到岛上的水)。一个单元格是边长为1的正方形。网格是矩形的,宽度和高度不超过100。确定岛的周长。

例子:

[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

答案: 16
解释: 周边是下图中的16条黄色条纹。


思路:

首先计算组成的岛的 1 的个数count,然后计算这些组成岛的 1 之间是否相邻between,每有一对相邻的 1(between),则周长 -2 ,因为相邻的 1 的两条边不能算入总的岛的周长中。故而,总的岛的周长4*count-2*between。


C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
	int islandPerimeter(vector<vector<int>>& grid) {
		int count = 0;
		int between = 0;
		for (int i = 0; i < grid.size(); i++) {
			for (int j = 0; j < grid[i].size(); j++) {
				if (grid[i][j] == 1) {
					count++;
					if ((i != 0) && (grid[i-1][j] == 1))
						between++;
					if ((j != 0) && (grid[i][j - 1] == 1))
						between++;
				}
			}
		}
		return 4 * count - 2 * between;
	}
};

int main()
{
	Solution s;
	vector<vector<int>> grid = { {0,1,0,0},{1,1,1,0,0},{0,1,0,0},{1,1,0,0} };
	int result;
	result = s.islandPerimeter(grid);
	cout << result;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tel_annie/article/details/80434970