問題(Easy):
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:
大意:
給你一個由二維整數(shù)網(wǎng)格組成的地圖,其中1表示土地,0表示水沸停。網(wǎng)格單元是水平/垂直接觸的(不能斜對角)良狈。網(wǎng)格完全被水包圍,確定只會有一座島嶼(比如黍特,一個或多個相連的土地單元)蛙讥。島嶼沒有湖(被島嶼包圍的周圍不與其他水相連的水)。一格單元是一個邊長為1的方格灭衷。網(wǎng)格是矩形的次慢,寬度和高度不會超過100。判斷島嶼的邊長翔曲。
例:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]答案:16
解釋:邊長是下圖中16個黃色條紋:
思路:
要注意對于邊界上的土地單元迫像,邊界也算邊長。我的想法是遍歷每個格子瞳遍,遇到土地時闻妓,判斷前后左右是否是邊界或水,是則給總邊長加1掠械。不過這樣比較慢由缆。
代碼(C++):
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
if (grid.size() == 0) return 0;
int res = 0;
int m = grid.size();
int n = grid[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
int temp = 0;
if (i-1 < 0) temp++;
if (i+1 == m) temp++;
if (j-1 < 0) temp++;
if (j+1 == n) temp++;
if (i > 0 && grid[i-1][j] == 0) temp++;
if (i < m-1 && grid[i+1][j] == 0) temp++;
if (j > 0 && grid[i][j-1] == 0) temp++;
if (j < n-1 && grid[i][j+1] == 0) temp++;
res = res + temp;
}
}
}
return res;
}
};
他山之石:
可以不用判斷那么多,首先記錄有多少個土地格子猾蒂,總邊長乘以4均唉,然后判斷有無相鄰的,有多少次相鄰的肚菠,則要減去其兩倍的邊長數(shù)浸卦。
這樣做的速度會快一倍。
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int count=0, repeat=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) repeat++;
if(j!=0 && grid[i][j-1] == 1) repeat++;
}
}
}
return 4*count-repeat*2;
}
};
合集:https://github.com/Cloudox/LeetCode-Record