In 2D binary matrix find the number of islands

前端 未结 2 1527
闹比i
闹比i 2020-12-21 02:29

I am trying to count the number of islands (a group of connected 1s forms an island) in a 2D binary matrix.

Example:

[
[1, 1, 0, 0, 0],
[0, 1, 0, 0,          


        
2条回答
  •  旧巷少年郎
    2020-12-21 03:04

    big hammer approach, for reference

    had to add structure argument np.ones((3,3)) to add diagonal connectivity

    import numpy as np
    from scipy import ndimage
    
    ary = np.array([
    [1, 1, 0, 0, 0],
    [0, 1, 0, 0, 1],
    [1, 0, 0, 1, 1],
    [0, 0, 0, 0, 0],
    [1, 0, 1, 0, 1]
    ])
    
    labeled_array, num_features = ndimage.label(ary, np.ones((3,3)))
    
    labeled_array, num_features
    Out[183]: 
    (array([[1, 1, 0, 0, 0],
            [0, 1, 0, 0, 2],
            [1, 0, 0, 2, 2],
            [0, 0, 0, 0, 0],
            [3, 0, 4, 0, 5]]), 5)
    

提交回复
热议问题