## 题目描述

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]]

Explanation: The perimeter is the 16 yellow stripes in the image below: ## 解法一

### 思路

1. 如果格子超出边界，则周长+1；否则
2. 如果格子是水，则周长+1

### Python

``````class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""

def is_water(i, j):
return i < 0 or j < 0 or i >= len(grid) or j >= len(grid) or grid[i][j] == 0

directions = ((0, -1), (0, 1), (-1, 0), (1, 0))
perimeter = 0
for (i, row) in enumerate(grid):
for (j, item) in enumerate(row):
if item == 1:
for direction in directions:
if is_water(i + direction, j + direction):
perimeter += 1
return perimeter``````

### Java

``````public class Solution {
public int islandPerimeter(int[][] grid) {
class Utils {
boolean isWater(int i, int j) {
return i < 0 || j < 0 || i >= grid.length || j >= grid.length || grid[i][j] == 0;
}
}
Utils utils = new Utils();
int[][] directions = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
int perimeter = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid.length; j++) {
if (grid[i][j] == 1) {
for (int[] direction : directions) {
if (utils.isWater(i + direction, j + direction)) {
perimeter++;
}
}
}
}
}
return perimeter;
}
}``````

### C++

``````class Solution {
public:
int islandPerimeter(vector <vector<int>> &grid) {
auto isWater = [&grid](int i, int j) {
return i < 0 || j < 0 || i >= grid.size() || j >= grid.size() || grid[i][j] == 0;
};
vector <vector<int>> directions{{0,  -1}, {0,  1}, {-1, 0}, {1,  0}};
int perimeter = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid.size(); j++) {
if (grid[i][j] == 1) {
for (auto &direction:directions) {
if (isWater(i + direction, j + direction)) {
perimeter++;
}
}
}
}
}
return perimeter;
}
};``````