class isLandsInGrid: def __init__(self , n , m): self.n = n self.m = m self.uf = UF(n*m , None) #we will use a linear representation for indices (i,j)=>i*n+j def numIslandsAfterAddingLands(self , positions): dirs = [(-1 , 0) , (1 , 0) , (0 , -1) , (0 , 1)] result = [] for pos in positions: linearPos = pos[0]*self.n + pos[1] self.uf.ids[linearPos] = linearPos self.uf.count += 1 for d in dirs: x = pos[1] + d[1] y = pos[0] + d[0] neighbor = linearPos + d[0]*self.n + d[1] if x < 0 or x >= self.n or y < 0 or y >= self.m or self.uf.ids[neighbor] is None: continue #in this case the neighbor is either not defined or it is not land if self.uf.ids[neighbor] != self.uf.ids[linearPos]: self.uf.union(linearPos , neighbor) result.append(self.uf.count) return result
def __init__(self , n , m): self.n = n self.m = m self.uf = UF(n*m , None) #we will use a linear representation for indices (i,j)=>i*n+j