class numIslands(object):
# This function finds the number of islands in the given grid
def findIslands(self, grid_input):
# If the grid is empty, return 0 as there are no islands
if not grid_input:
return 0
count_islands = 0 # Initialize a counter for the number of islands
rows = len(grid_input) # Get the number of rows in the grid
cols = len(grid_input[0]) # Get the number of columns in the grid
row = 0 # Start from the first row
# Traverse through each cell of the grid
while row < rows:
col = 0 # Start from the first column in each row
while col < cols:
# If the current cell contains '1' (part of an island)
if grid_input[row][col] == "1":
# Perform DFS to mark all connected land ('1') as visited
self.graphdfs(grid_input, row, col)
count_islands += 1 # Increment the island count after DFS
col += 1 # Move to the next column
row += 1 # Move to the next row
return count_islands # Return the total number of islands found
# This function performs Depth-First Search (DFS) to explore connected land cells
def graphdfs(self, grid, row, col):
# Base case: If the cell is out of bounds or not land ('1'), return
if (
row < 0
or col < 0
or row >= len(grid)
or col >= len(grid[0])
or grid[row][col] != "1"
):
return
# Mark the current cell as visited by setting it to '#'
grid[row][col] = "#"
# Explore all four directions (down, up, right, left) recursively
self.graphdfs(grid, row + 1, col) # Down
self.graphdfs(grid, row - 1, col) # Up
self.graphdfs(grid, row, col + 1) # Right
self.graphdfs(grid, row, col - 1) # Left
# Helper function to print the grid like a matrix
def printGrid(self, grid):
for row in grid:
print(" ".join(row))
# Example grid input
grid_input = [
["1", "1", "0", "0"],
["1", "1", "0", "0"],
["0", "0", "0", "0"],
["0", "0", "0", "1"],
]
# Creating an instance of numIslands class
solution = numIslands()
# Print the grid in matrix form before calling the function
print("Initial Grid:")
solution.printGrid(grid_input)
# Calling the function with the grid input
num_islands = solution.findIslands(grid_input)
# Print the grid in matrix form after islands are marked
print("\nGrid after marking visited islands:")
solution.printGrid(grid_input)
# Output the result
print("\nNumber of islands:", num_islands)