# Leetcode 463. Island Perimeter 給定一個二維陣列,數字為1則會陸地,數字為0則為海洋,其中包含唯一一座島嶼,並且島嶼中不包含湖泊,計算島嶼的周長。 ## 想法 針對每一個1,去計算其上下左右是否為1,是的會將周長4去減去1,即可得到答案。 程式碼: ``` def islandPerimeter(self, grid: List[List[int]]) -> int: x_len = len(grid[0]) y_len = len(grid) print(x_len, y_len) ans = 0 for i in range(y_len): for j in range(x_len): if(grid[i][j]!=1): continue tag = 4 if(i-1>=0): if(grid[i-1][j]==1): tag-=1 if(i+1<y_len): if(grid[i+1][j]==1): tag-=1 if(j-1>=0): if(grid[i][j-1]==1): tag-=1 if(j+1<x_len): if(grid[i][j+1]==1): tag-=1 ans+=tag return ans ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up