Quantcast
Channel: Find maximum area of island in matrix - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 4

Answer by Graipher for Find maximum area of island in matrix

$
0
0

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.


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>