7/15/2017

Leetcode 463. Island Perimeter solution with SUPER EASY explanation 超简单思路

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:

Think:
Suppose I have only 1 land in the beginning, and the perimeter is 4.
1,0,0,0
0,0,0,0
0,0,0,0
if I gonna add 1 land, the graph would be like:
1,1,0,0
0,0,0,0
0,0,0,0
The perimeter is 6.
Continue doing this, obviously, I can figure out the perimeter match this pattern:
perimeter = 4+(n-1)*2
But there is an exception if the island looks like
1,1,0,0
1,0,0,0
0,0,0,0
when I add a new land in [2,2] the perimeter won't change
1,1,0,0
1,1,0,0
0,0,0,0
Which means, in the formula: perimeter = 4+(n-1)*2
the n needs to minus 1.

Solution:

No comments:

Post a Comment