Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

count number of 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 :: Create MySQL table from Python 
Python :: python hand tracking module 
Python :: python split pdf pages 
Python :: python filter array 
Python :: save dictionary python 
Python :: seaborn axis limits 
Python :: if type is string python 
Python :: keyerror dislike_count pafy 
Python :: run django app locally 
Python :: python3 base64 encode basic authentication 
Python :: get number of missing values dataframe 
Python :: how to save matplotlib figure to png 
Python :: tqdm for jupyter notebook 
Python :: print numpy version 
Python :: python duplicate file 
Python :: with font type stuff python turtle 
Python :: matplotlib grid 
Python :: split a path into all subpaths 
Python :: celsius to fahrenheit in python 
Python :: html to json python 
Python :: check corently installed epython version 
Python :: how to remove plotly toolbar 
Python :: how to get unix timestamp in python 
Python :: only keep few key value from dict 
Python :: random word generator python 
Python :: python get arguments 
Python :: np array value count 
Python :: python discord webhook 
Python :: standardize columns in pandas 
Python :: To check pip version 
ADD CONTENT
Topic
Content
Source link
Name
3+5 =