2018年1月25日 星期四

[LeetCode] 463. Island Perimeter

轉自LeetCode

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>

這題原本想用 BFS 的方式去解,但實際是沒那麼複雜

想法如下
  • 由上往下,由左至右開始掃描,這樣只要檢查右邊和下面,是不是還有連接的島嶼即可。因為題目有明確說,只會有一座島嶼,且中間不會有湖
  • 每多一塊島嶼,邊的數目多4個,但只要它右邊或下面有連接其它島嶼,那麼邊數會減2
code如下

C++

Java

沒有留言:

張貼留言