You are given row x col
grid
representing a map where grid[i][j] = 1
represents land and grid[i][j] = 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", meaning the water inside 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:
Example 2:
Constraints:
row
== grid.length
col
== grid[i].length
row
, col
<= 100grid[i][j]
is 0 or 1grid
這題我對每個格子都看其左上角,只要是土地對海水或是海稅對土地,就會有邊界出現,如此走完 matrix 可以看完大部分的邊界,但有些卻漏的,例如最右邊、最下面看不到,而我又不希望重複看,所以就特別寫出來判斷了。最後要注意最上面跟最左邊因為 matrix 取值不要有取到 -1 的情況,要把 i, j == 0
的情況也抓出來先判斷。
因為走訪完全部的 matrix,所以是
沒有特別存什麼參數,所以是