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:
题目大意:一个二维数组,0代表水域,1代表陆地。有且只有一整块陆地,求陆地的周长。
解题思路:遍历二位数组,对每个格子计算这个格子在整个陆地中的周长是多少。
如果是0,则代表水域,不用计算周长;
如果是1,则代表陆地,则分别根据其上下左右的情况计算出这个格子在整个陆地中的周长是多少。
代码如下:(141ms,beats 81.03%)
public class IslandPerimeter {
//计算每个格子在整个陆地中占据多少周长的函数
public int getPerimeter(int[][] grid, int x, int y, int width, int height) {
int perimeter = 0;
if (grid[y][x] == 0)
return perimeter;
if (x == 0)
perimeter++;
else {
if (grid[y][x - 1] == 0)
perimeter++;
}
if (x == width - 1)
perimeter++;
else {
if (grid[y][x + 1] == 0)
perimeter++;
}
if (y == 0)
perimeter++;
else {
if (grid[y - 1][x] == 0)
perimeter++;
}
if (y == height - 1)
perimeter++;
else {
if (grid[y + 1][x] == 0)
perimeter++;
}
return perimeter;
}
public int islandPerimeter(int[][] grid) {
int perimeter = 0;
int height = grid.length;
int width = grid[0].length;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
perimeter += getPerimeter(grid, x, y, width, height);
}
}
return perimeter;
}
}