-
标签:
哈希表
-
难度:
简单
- 题目描述

- 我的解法
被蚊子折磨了一晚上啊,困得要死,今天脑子不灵光,先用一个简答的解法好了:遍历 grid
, 若块的值为 1
,land
计数加1, 查看其下方或右方的邻接块是否为 1
, 若为 1
则 touch
计数加 1
, 最后结果为: land * 4 - touch * 2
. 但是这种方法未能充分挖掘题目信息,应该还有更优雅的解法,懒得去看 discuss
了.
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
land = 0
touch = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if(grid[i][j] == 1):
land += 1
if(i < len(grid) - 1 and grid[ i+ 1][j] == 1):
touch += 1
if(j < len(grid[0]) - 1 and grid[i][j + 1] ==1):
touch += 1
return land * 4 - touch * 2
- 其他解法
暂略。
网友评论