题目要求
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:
Input:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:
用一个二维数组来表示一块岛屿的土地情况,其中 1 代表土地,0 代表海洋。要求计算出岛屿的周长。题目中特别强调了不存在内陆湖的存在,其实是变相的降低了题目的难度。即我们只要看到 1 和 0 相邻,就可以判断出到了岛的边缘。
思路和代码
这题不难,直观的来看,其实只要判断出这一块土地几面临海就知道需要加上几条边长。临海的判断有两个,一个是这块地位于数组的边缘,一个是这块地相邻的元素为 0,即海洋。遇到这种情况我们就需要将边界领土加一即可。代码如下:
public int islandPerimeter(int[][] grid) {
int perimeter = 0;
for(int i = 0 ; i<grid.length ; i++) {for(int j = 0 ; j<grid[i].length ; j++) {int num = grid[i][j];
if(num == 1) {
// 上方临海
if(i == 0 || grid[i-1][j]==0) perimeter++;
// 左侧临海
if(j == 0 || grid[i][j-1]==0) perimeter++;
// 右侧临海
if(i == grid.length-1 || grid[i+1][j]==0) perimeter++;
// 下方临海
if(j == grid[i].length-1 || grid[i][j+1]==0) perimeter++;
}
}
}
return perimeter;
}