-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0463_Island_Perimeter.py
77 lines (69 loc) · 1.94 KB
/
0463_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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from typing import List
from unittest import TestCase, main
def islandPerimeter(grid: List[List[int]]) -> int:
borders = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == 1:
top_is_land = row - 1 >= 0 and grid[row - 1][col] == 1
left_is_land = col - 1 >= 0 and grid[row][col - 1] == 1
if top_is_land and left_is_land:
continue
elif top_is_land or left_is_land:
borders += 2
elif not top_is_land and not left_is_land:
borders += 4
return borders
class Test(TestCase):
def test_given_case(self):
self.assertEqual(
islandPerimeter([
[0, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 0, 0],
[1, 1, 0, 0]
]),
16
)
def test_single_island(self):
self.assertEqual(
islandPerimeter([
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]),
4
)
def test_vertical_strip(self):
self.assertEqual(
islandPerimeter([
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0]
]),
10
)
def test_horizontal_strip(self):
self.assertEqual(
islandPerimeter([
[0, 0, 0, 0],
[1, 1, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0]
]),
10
)
def test_square_island(self):
self.assertEqual(
islandPerimeter([
[0, 0, 0, 0],
[0, 1, 1, 1],
[0, 1, 1, 1],
[0, 1, 1, 1]
]),
12
)
if __name__ == "__main__":
main()