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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章