If you were trying to solve this problem in real life (and not on leetcode), I would use existing tools for this. Specifically, with scikit-image
this becomes rather easy:
import numpy as npfrom skimage import measuredef largest_island(grid): labels = measure.label(grid, connectivity=1) return max(region.area for region in measure.regionprops(labels))if __name__ == "__main__": grid = np.array([[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]]) print(largest_island(grid))
This uses skimage.measure.label
to give each connected area a unique label, where areas can only be connected horizontally and vertically, but not diagonally. It then uses skimage.measure.regionprops
, which calculates properties of labeled regions.
Unfortunately, scikit-image
seems not to be included on leetcode.