Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR 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
Source by eolnuha.com #
 
PREVIOUS NEXT
Tagged: #count #number #islands #python
ADD COMMENT
Topic
Name
3+4 =