-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathIsland Perimeter.py
52 lines (42 loc) · 1.34 KB
/
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from typing import List
class Solution:
"""
Time: O(n*m)
Memory: O(1)
"""
LAND = 1
WATER = 0
def islandPerimeter(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
perimeter = 0
for r in range(n):
for c in range(m):
if grid[r][c] != self.LAND:
continue
if r == 0 or grid[r - 1][c] == self.WATER:
perimeter += 1
if r == n - 1 or grid[r + 1][c] == self.WATER:
perimeter += 1
if c == 0 or grid[r][c - 1] == self.WATER:
perimeter += 1
if c + 1 == m or grid[r][c + 1] == self.WATER:
perimeter += 1
return perimeter
class Solution:
"""
Time: O(n*m)
Memory: O(1)
"""
LAND = 1
WATER = 0
def islandPerimeter(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
return sum(
sum([
r == 0 or grid[r - 1][c] == self.WATER,
r == n - 1 or grid[r + 1][c] == self.WATER,
c == 0 or grid[r][c - 1] == self.WATER,
c + 1 == m or grid[r][c + 1] == self.WATER
]) for r in range(n)
for c in range(m) if grid[r][c] == self.LAND
)