你是在一個二維整數網格,1個代表0個代表土地和水形成圖。網格連接水平/垂直(不斜)。網格是完全被水環繞,有一個島(即一個或多個連接的土地方格)。島上沒有“湖”(水裏面沒有連接到該島附近的水)。一個方格是一個正方形的邊長爲1。網格是矩形,寬度和高度不超過100。確定該島的周長。
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:
public class Solution {
public int islandPerimeter(int[][] grid) {
int islands = 0, neighbours = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 1) {
islands++; // count islands
if (i < grid.length - 1 && grid[i + 1][j] == 1) neighbours++;
if (j < grid[i].length - 1 && grid[i][j + 1] == 1) neighbours++;
}
}
}
return islands * 4 - neighbours * 2;
}
}