forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisland-perimeter.py
31 lines (24 loc) · 996 Bytes
/
island-perimeter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Time: O(m * n)
# Space: O(1)
import operator
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
count, repeat = 0, 0
for i in xrange(len(grid)):
for j in xrange(len(grid[i])):
if grid[i][j] == 1:
count += 1
if i != 0 and grid[i - 1][j] == 1:
repeat += 1
if j != 0 and grid[i][j - 1] == 1:
repeat += 1
return 4*count - 2*repeat
# Since there are no lakes, every pair of neighbour cells with different values is part of the perimeter
# (more precisely, the edge between them is). So just count the differing pairs, both horizontally and vertically
# (for the latter I simply transpose the grid).
def islandPerimeter2(self, grid):
return sum(sum(map(operator.ne, [0] + row, row + [0])) for row in grid + map(list, zip(*grid)))