7/14 每日一題(計算島嶼邊界數量)
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:

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
Constraints:
row == grid.lengthcol == grid[i].length1 <= row, col <= 100grid[i][j]is0or1.- There is exactly one island in
grid.
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
#初始化 列
row=0
stripes=0
for i in grid:
col=0 # 初始化行
squara=i.count(1) #計算幾個正方形
stripes += squara*4 #計算幾個邊界,不考慮邊界共有
for j in i:
#檢查邊界共有情況
next_row=row+1
up_row=row-1
left_col=col-1
right_col=col+1
if j==1:
if next_row <len(grid) and grid[next_row][col]==1:
stripes -=1
if up_row >=0 and grid[up_row][col]==1:
stripes -=1
if right_col <len(i) and grid[row][right_col]==1:
stripes -=1
if left_col >=0 and grid[row][left_col]==1:
stripes -=1
col +=1 #向下一行移動
row +=1 #向下一列移動
return stripes
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁