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.
Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image above.
Example 2:
Input: grid = [[1]]
Output: 4
Example 3:
Input: grid = [[1,0]]
Output: 4
row == grid.length
col == grid[i].length
1 <= row, col <= 100
grid[i][j]
is 0
or 1
.grid
.先用一層 for 迴圈遍歷所有的 grid,遍歷的過程每一格使用 DFS 去找所有是 1 的格子,並將它清為 0。
You are given row x col grid representing a map where
這代表它會給我們 row, col 這兩個參數嗎? 他不會給,要自己設
又因為它需要計算的是邊長,所以我改為 grid 清為 2,然後如果有重疊的邊長會附蓋掉,所以設定數個針對相鄰個子的判別式將覆蓋掉的邊常扣掉。
寫得很丑…然後發現其實不用 DFS 就可以解。
判斷每一格的上下左右鄰居,若有水則 +1
,另外如果為邊界也同樣 +1