Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

count number of matrix islands python

def count_islands(matrix):
  islands = 0
  for row in range(len(matrix)):
    for column in range(len(matrix[row])):
      #if a '1' is encountered we will increase islands by one and call a function that removes it
      if matrix[row][column] == '1':
        islands += 1
        remove_island(matrix, row, column)
  return islands

def remove_island(matrix, row, column):
  if matrix[row][column] == '1':
    matrix[row][column] = '0' #This removes or turns the current '1' to '0'

    #if there are '1's adjacent to the current '1'
    #call remove_island() until a '1' is no longer detected

    if row > 0:
      remove_island(matrix, row - 1, column)
    if row < len(matrix) - 1:
      remove_island(matrix, row + 1, column)
    if column > 0:
      remove_island(matrix, row, column - 1)
    if column < len(matrix[0]) - 1:
      remove_island(matrix, row, column + 1)

test_case_0 = [
  ['1','1','0','0','0'],
  ['0','1','0','0','1'],
  ['1','0','0','1','1'],
  ['1','0','0','0','0'],
  ['1','0','1','0','1']
]

test_case_1 = [
  ['1','1','0','1','0'],
  ['1','1','0','0','1'],
  ['1','0','0','1','1'],
  ['1','0','0','0','0'],
  ['1','0','1','1','1']
]

print(count_islands(test_case_0)) #Expected output: 5
print(count_islands(test_case_1)) #Expected output: 4
Comment

PREVIOUS NEXT
Code Example
Python :: how to get the size of an object in python 
Python :: import status in django rest framework 
Python :: How to perform run-length encoding in Python? 
Python :: discord.py intents 
Python :: python time now other timezone 
Python :: save numpy arrayw with PIL 
Python :: python loop through files in directory recursively 
Python :: put text on image python 
Python :: purge command discord.py 
Python :: tensorflow load h5 model 
Python :: count missing values by column in pandas 
Python :: print first dictionary keys python 
Python :: set cuda visible devices python 
Python :: colab cuda version 
Python :: python time using timeit module 
Python :: how to get ipconfig from python 
Python :: python find all pairs in list 
Python :: python randomise between 0 or 1 
Python :: how to loop in python 
Python :: write dataframe to csv python 
Python :: check python version ubuntu 
Python :: delete image with python 
Python :: python change filename 
Python :: matplotlib remove ticks and lines 
Python :: tkinter canvas remove border 
Python :: python print in color 
Python :: create an array with same value python 
Python :: increase limit of recusrion python 
Python :: column standardization pandas 
Python :: check pip version 
ADD CONTENT
Topic
Content
Source link
Name
7+3 =