mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
Merge pull request #899 from kai0456/master
Add python3 solution for the quesiton 0463. Thanks! -Kai
This commit is contained in:
@ -120,6 +120,41 @@ class Solution {
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
|
Reference in New Issue
Block a user