305. Number of Islands II
Input:
m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]]
Output:
[1,1,2,3]0 0 0
0 0 0
0 0 01 0 0
0 0 0 Number of islands = 1
0 0 01 1 0
0 0 0 Number of islands = 1
0 0 0Last updated
Was this helpful?
Input:
m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]]
Output:
[1,1,2,3]0 0 0
0 0 0
0 0 01 0 0
0 0 0 Number of islands = 1
0 0 01 1 0
0 0 0 Number of islands = 1
0 0 0Last updated
Was this helpful?
Was this helpful?
1 1 0
0 0 1 Number of islands = 2
0 0 01 1 0
0 0 1 Number of islands = 3
0 1 0class Solution(object):
def numIslands2(self, m, n, positions):
"""
:type m: int
:type n: int
:type positions: List[List[int]]
:rtype: List[int]
"""
def find(parent, val):
while parent[val] != val:
'''
Path Compression:
parent[val] = parent[parent[val]]
'''
val = parent[val]
return val
def union(x, y):
'''
Union by Rank:
if rank[x] > rank[y]:
x, y = y, x
rank[y] += rank[x] == rank[y]
'''
parent[find(x)] = find(y)
return find(y)
parent , rank = [-1] * (m * n), [0] * (m * n)
d = [0, 1 , 0 , -1, 0]
cnt = 0
ans = []
if m < 1 or n < 1:
return []
for pos in positions:
cnt += 1
root = n * pos[0] + pos[1]
parent[root] = root
# expanding its neightbor: once find there is a island, connect them
for i in range(4):
x , y = pos[0] + d[i] , pos[1] + d[i + 1]
nb = x * n + y
if x >= 0 and x < m and y >= 0 and y < n and parent[nb] != -1:
rootN = find(parent, nb)
if root != rootN:
root = union (root, rootN)
cnt -= 1
ans.append(cnt)
return ans