In 2D binary matrix find the number of islands

前端 未结 2 1517
闹比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 02:47

    Your algorithm is almost correct except for the line 21:

    if r != i and c != j:
        cnt += count_houses(mat, visited, r, c)
    

    Instead you want to use or as you want to continue counting provided at least one of the coordinate is not the same as your center.

    if r != i or c != j:
        cnt += count_houses(mat, visited, r, c)
    

    An alternate and more intuitive way to write this would be the following

    if (r, c) != (i, j):
        cnt += count_houses(mat, visited, r, c)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题