title: How to find cluster sizes in 2D numpy array?
body: <p>My problem is the following,</p>
  
  <p>I have a 2D numpy array filled with 0 an 1, with an absorbing boundary condition (all the outer elements are 0) , for example: </p>
  
  <pre><code>[[0 0 0 0 0 0 0 0 0 0]
   [0 0 1 0 0 0 0 0 0 0]
   [0 0 1 0 1 0 0 0 1 0]
   [0 0 0 0 0 0 1 0 1 0]
   [0 0 0 0 0 0 1 0 0 0]
   [0 0 0 0 1 0 1 0 0 0]
   [0 0 0 0 0 1 1 0 0 0]
   [0 0 0 1 0 1 0 0 0 0]
   [0 0 0 0 1 0 0 0 0 0]
   [0 0 0 0 0 0 0 0 0 0]]
  </code></pre>
  
  <p>I want to create a function that takes this array and its linear dimension L as input parameters, (in this case L = 10) and returns the list of cluster sizes of this array.</p>
  
  <p>By "clusters" I mean the isolated groups of elements 1 of the array  </p>
  
  <p>the array element [ i ][ j ] is isolated if all its neighbours are zeros, and its neighbours are the elements: </p>
  
  <pre><code>[i+1][j]
  [i-1][j]
  [i][j+1]
  [i][j-1]
  </code></pre>
  
  <p>So in the previous array we have 7 clusters of sizes (2,1,2,6,1,1,1)</p>
  
  <p>I tried to complete this task by creating two functions, the first one is a recursive function:</p>
  
  <pre><code>def clust_size(array,i,j):
  
      count = 0
  
      if array[i][j] == 1:
  
          array[i][j] = 0
  
          if array[i-1][j] == 1:
  
              count += 1
              array[i-1][j] = 0
              clust_size(array,i-1,j)
  
          elif array[i][j-1] == 1:
  
              count += 1
              array[i-1][j] = 0
              clust_size(array,i,j-1)
  
          elif array[i+1][j] == 1:
  
              count += 1
              array[i-1][j] =  0
              clust_size(array,i+1,j)
  
          elif array[i][j+1] == 1:
  
              count += 1
              array[i-1][j] = 0
              clust_size(array,i,j+1)
  
      return count+1         
  </code></pre>
  
  <p>and it should return the size of one cluster. Everytime the function finds an array element equal to 1 it increases the value of the counter "count" and changes the value of the element to 0, in this way each '1' element it's counted just one time.
  If one of the neighbours of the element is equal to 1 then the function calls itself on that element. </p>
  
  <p>The second function is:</p>
  
  <pre><code>def clust_list(array,L):
  
      sizes_list = []
  
      for i in range(1,L-1):
          for i in range(1,L-1):
  
             count = clust_size(array,i,j)
  
             sizes_list.append(count)
  
      return sizes_list
  </code></pre>
  
  <p>and it should return the list containing the cluster sizes. The for loop iterates from 1 to L-1 because all the outer elements are 0.</p>
  
  <p>This doesn't work and I can't see where the error is...</p>
  
  <p>I was wondering if maybe there's an easier way to do it.</p>