forked from shijbian/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathisland-perimeter.py
More file actions
77 lines (67 loc) · 2.37 KB
/
island-perimeter.py
File metadata and controls
77 lines (67 loc) · 2.37 KB
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
# Time: O(m * n)
# Space: O(1)
# You are given a map in form of a two-dimensional integer grid
# where 1 represents land and 0 represents water.
# Grid cells are connected horizontally/vertically (not diagonally).
# The grid is completely surrounded by water, and there is exactly one island
# (i.e., one or more connected land cells).
# The island doesn't have "lakes" (water inside that isn't connected to
# the water around the island). One cell is a square with side length 1.
# The grid is rectangular, width and height don't exceed 100.
# Determine the perimeter of the island.
#
# Example:
#
# [[0,1,0,0],
# [1,1,1,0],
# [0,1,0,0],
# [1,1,0,0]]
#
# Answer: 16
import operator
#my solution
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
if n == 0: return 0
m = len(grid[0])
if m == 0: return 0
cnt = 0
for i in range(n):
for j in range(m):
if grid[i][j] == 0:
continue
if i == 0 or grid[i-1][j] == 0:
cnt += 1
if j == 0 or grid[i][j-1] == 0:
cnt += 1
if i == n - 1 or grid[i+1][j] == 0:
cnt += 1
if j == m - 1 or grid[i][j+1] == 0:
cnt += 1
return cnt
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)))