463. Island Perimeter
Problem description:
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:
Solution:
Count the total number of grid that is 1 from top to down
and from left to right
.
When we’re counting the perimeter, if there’s any neighbor of a grid, it will cancel off two edges.
ex:1
2
3
4+--+ +--+ +--+--+
| | + | | -> | |
+--+ +--+ +--+--+
2 islands
1 | 4 + 4 - ? = 6 -> ? = 2 |
While we’re scanning the grid, we need to know how many neighbor does this grid have. Since we’re scanning from top to down, we only need to count the neighbor its row is above the grid.
Same thing about the neighbor that has different column, only need to count neighbor that is on the left side.
1 | class Solution: |
1 | class Solution { |
time complexity: $O(mn)$
space complexity: $O(1)$
reference:
https://goo.gl/5rZHRg