LeetCode 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.

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:

 

 


题目标签:Hash Table

 

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

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

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

 

 

 

Java Solution:

Runtime beats 91.70% 

完成日期:06/07/2017

关键词:Array

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

 1 class Solution 
 2 {
 3     public int islandPerimeter(int[][] grid) 
 4     {
 5         int res = 0;
 6         
 7         for(int i=0; i)
 8         {
 9             for(int j=0; j)
10             {
11                 if(grid[i][j] == 1) // for each land, only check its up and left neighbor cell
12                 {
13                     res += 4;
14                     
15                     if(i > 0 && grid[i-1][j] == 1) // if up cell is 1, res - 2
16                         res -= 2;
17                     if(j > 0 && grid[i][j-1] == 1) // if left cell is 1, res - 2
18                         res -= 2;    
19                 }
20                 
21             }
22         }
23         
24         return res;
25     }
26 }

参考资料:

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

 

LeetCode 题目列表 - LeetCode Questions List

转载于:https://www.cnblogs.com/jimmycheng/p/7812865.html

你可能感兴趣的:(LeetCode 463. Island Perimeter (岛的周长))