forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path305.number-of-islands-ii.py
60 lines (46 loc) · 1.55 KB
/
305.number-of-islands-ii.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
class UnionFind(object):
def __init__(self):
self.graph = {}
def add(self, node):
self.graph[node] = node
def find(self, node):
if self.graph[node] == node:
return node
self.graph[node] = self.find(self.graph[node])
return self.graph[node]
def connect(self, a, b):
root_a = self.find(a)
root_b = self.find(b)
if root_a != root_b:
self.graph[root_a] = root_b
return True
return False
DIRECTIONS = [[0, 1],[-1, 0],[0, -1],[1, 0]]
class Solution(object):
def numIslands2(self, m, n, positions):
"""
:type m: int
:type n: int
:type positions: List[List[int]]
:rtype: List[int]
"""
islands = set()
uf = UnionFind()
size = 0
res = []
for pos in positions:
x = pos[0]
y = pos[1]
if (x, y) not in islands:
islands.add((x, y))
uf.add((x, y))
size += 1
for direction in DIRECTIONS:
new_x = x + direction[0]
new_y = y + direction[1]
if (0 <= new_x < m and 0 <= new_y < n):
if (new_x, new_y) in islands:
if (uf.connect((x, y), (new_x, new_y))):
size -= 1
res.append(size)
return res