fix:岛屿周长

上级 5b06ba0f
......@@ -4,4 +4,4 @@ import requests
url = 'https://www.baidu.com/'
values = {'name': 'John', 'age': 25}
response = requests.post(url, data=values)
print(response.text)
print(response.text)
\ No newline at end of file
"""
岛屿的周长
"""
from typing import List
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
# x轴和y轴
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
result = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
# 如果是水域直接跳过,只处理岛屿的格子
if grid[i][j] == 1:
# 存在岛屿则重置
count = 0
# 计算每个岛屿右左上下是否有水域或者是边界
for x, y in directions:
ix = i + x
jy = j + y
# 和岛屿连接的水域边,针对的是当前行的加减,当前行的坐标小于0或者大于等于最大index则说明是在边界
if ix < 0 or ix >= len(grid) or jy < 0 or jy >= len(grid[0]) or grid[ix][jy] == 0:
count += 1
result += count
return result
if __name__ == '__main__':
result = Solution().islandPerimeter([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]])
print(result)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册