Merge pull request #899 from kai0456/master

Add python3 solution for the quesiton 0463. Thanks! -Kai
This commit is contained in:
程序员Carl
2021-11-16 12:41:45 +08:00
committed by GitHub

View File

@ -120,6 +120,41 @@ class Solution {
``` ```
Python Python
### 解法1:
扫描每个cell,如果当前位置为岛屿 grid[i][j] == 1 从当前位置判断四边方向如果边界或者是水域证明有边界存在res矩阵的对应cell加一。
```python3
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
# 创建res二维素组记录答案
res = [[0] * n for j in range(m)]
for i in range(m):
for j in range(len(grid[i])):
# 如果当前位置为水域不做修改或reset res[i][j] = 0
if grid[i][j] == 0:
res[i][j] = 0
# 如果当前位置为陆地往四个方向判断update res[i][j]
elif grid[i][j] == 1:
if i == 0 or (i > 0 and grid[i-1][j] == 0):
res[i][j] += 1
if j == 0 or (j >0 and grid[i][j-1] == 0):
res[i][j] += 1
if i == m-1 or (i < m-1 and grid[i+1][j] == 0):
res[i][j] += 1
if j == n-1 or (j < n-1 and grid[i][j+1] == 0):
res[i][j] += 1
# 最后求和res矩阵这里其实不一定需要矩阵记录可以设置一个variable res 记录边长,舍矩阵无非是更加形象而已
ans = sum([sum(row) for row in res])
return ans
```
Go Go