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:

LeetCode 463. Island Perimeter (岛的周长)-LMLPHP


题目标签:Hash Table

  题目给了我们一个2d grid,1 代表 岛;0 代表 海水,让我们找到岛的周长。

  遍历grid,对于等于1 的cell: 首先res += 4,把它的周长先加上;然后检查它的 上方 和左边 的cell,如果是1的,就减去2。

  因为我们的遍历方向是从上到下,从左到右,所以我们只需要检查 上方 和 左边的格子就可以了。

Java Solution:

Runtime beats 91.70%

完成日期:06/07/2017

关键词:Array

关键点:只需要检查上面和左边的邻居

 class Solution
{
public int islandPerimeter(int[][] grid)
{
int res = 0; for(int i=0; i<grid.length; i++)
{
for(int j=0; j<grid[0].length; j++)
{
if(grid[i][j] == 1) // for each land, only check its up and left neighbor cell
{
res += 4; if(i > 0 && grid[i-1][j] == 1) // if up cell is 1, res - 2
res -= 2;
if(j > 0 && grid[i][j-1] == 1) // if left cell is 1, res - 2
res -= 2;
} }
} return res;
}
}

参考资料:

https://discuss.leetcode.com/topic/68786/clear-and-easy-java-solution

LeetCode 题目列表 - LeetCode Questions List

05-11 17:49