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:
1
2
3
4
5
6
7
8
9 > >[[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:
>
>
题意就是说有多个相互接壤的土地连成一个岛,然后求这个的岛的周长
思路也很简单,但是自己一开始采用了错误的做法(一直想用一行的周长规律去推整个岛的周长规律),导致一直WA。
其实只要数一数有多少条边是共享(包括行和行共享与列和列共享)的就可以了,每一条共同边会让周长减去2,所以最后答案就可以表达为
4 x 总块数 - 2 x 共同边数。
Wrong Answer版本:
1 | class Solution { |
Accepted版本
1 | class Solution { |