一、问题描述:
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 (num),以及每个1和其他1相邻的个数(del), 返回 num * 4 - del
public class Solution {
public int comOne(int[][] grid, int i, int j) {
int re = 0;
// 第一行:
if (i == 0) {
if (j == 0) {
re = re + grid[i][j + 1] + grid[i + 1][j];
return re;
}
if (j == grid[0].length - 1) {
re = re + grid[i][j - 1] + grid[i + 1][j];
return re;
} else {
re = re + grid[i][j + 1] + grid[i][j - 1] + grid[i + 1][j];
return re;
}
}
// 第一列:
if (j == 0) {
if (i == grid.length - 1) {
re = re + grid[i - 1][j] + grid[i][j + 1];
return re;
} else {
re = re + grid[i - 1][j] + grid[i][j + 1] + grid[i + 1][j];
return re;
}
}
// 最后一行:
if (i == grid.length - 1) {
if (j == grid[0].length - 1) {
re = re + grid[i - 1][j] + grid[i][j - 1];
return re;
} else {
re = re + grid[i - 1][j] + grid[i][j + 1] + grid[i][j - 1];
return re;
}
}
// 最后一列:
if (j == grid[0].length - 1) {
re += grid[i - 1][j] + grid[i + 1][j] + grid[i][j - 1];
return re;
}
else {
re += grid[i - 1][j] + grid[i + 1][j] + grid[i][j - 1] + grid[i][j + 1];
}
return re;
}
public int islandPerimeter(int[][] grid) {
int length = grid.length;
int width = grid[0].length;
int sum = 0;
if (length == 1) {
for (int j = 0; j < width; j++) {
sum += grid[0][j];
}
return sum * 4 - 2 * (sum - 1);
}
if (width == 1) {
for (int j = 0; j < length; j++) {
sum += grid[j][0];
}
return sum * 4 - 2 * (sum - 1);
}
int del = 0;
for (int i = 0; i < length; i++) {
for (int j = 0; j < width; j++) {
if (grid[i][j] == 1) {
sum++;
del += comOne(grid, i, j);
}
}
}
return sum * 4 - del;
}
}
三、代码: