463. Island Perimeter 海岛周长
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.
翻译:给出一个二维整数网格形式的地图,其中1表示土地,0表示水。网格单元水平/垂直(不对角线)连接。网格完全被水包围,只有一个岛屿(即一个或多个连接的地面细胞)。岛上没有“湖泊”(水内没有连接到岛上的水)。一个单元格是具有边长为1的正方形。网格为矩形,宽度和高度不超过100.确定岛的周长。
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
答案:16
说明:周长是16条黄色条纹图片如下:
public class Solution{
public int islandPerimeter(int[][] grid){
if(grid.length == 0 || grid == null)
return 0;
int neighbors = 0, int islands = 0;
for(int i = 0; i < grid.length; i++)
for(int j = 0; j < grid[i].length; j++){
if(gird[i][j] == 1){
island++;
if(i + 1 < grid.length && grid[i+1][j] == 1)
neighbors++;
if(j + 1 < grid[i].length && grid[i][j+1] == 1)
neightbors++;
}
}
return islands * 4 - neighbors * 2;
}
}
- 解决思路:循环遍历数组
- 每当走到一个island时,我们只往右和下看,这样能防止重复看neighbor
每看到一个Neighbor,相当于
+–+ +–+ +–+–+
| | + | | -> | |
+–+ +–+ +–+–+
最后return islands * 4 - neighbor * 2
为什么是Neighbor*2,由上图可知,只要有一个邻居,就会有一个边被两个islands共享,所以要减去这重复就算的2.