forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnumber-of-distinct-islands.py
More file actions
31 lines (27 loc) · 919 Bytes
/
number-of-distinct-islands.py
File metadata and controls
31 lines (27 loc) · 919 Bytes
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(m * n)
class Solution(object):
def numDistinctIslands(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
directions = {'l':[-1, 0], 'r':[ 1, 0], \
'u':[ 0, 1], 'd':[ 0, -1]}
def dfs(i, j, grid, island):
if not (0 <= i < len(grid) and \
0 <= j < len(grid[0]) and \
grid[i][j] > 0):
return False
grid[i][j] *= -1
for k, v in directions.iteritems():
island.append(k);
dfs(i+v[0], j+v[1], grid, island)
return True
islands = set()
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
island = []
if dfs(i, j, grid, island):
islands.add("".join(island))
return len(islands)