In the counting number of islands problem, I noticed that one of the solution from internet is as follows
def visitIslandDFS(grid, i, j):
if (i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0])):
return # return, if it is not a valid cell
if (grid[i][j] == '0'):
return # return, if it is a water cell
grid[i][j] = '0' # mark the cell visited by making it a water cell
visitIslandDFS(grid, i + 1, j) # lower cell
visitIslandDFS(grid, i - 1, j) # upper cell
visitIslandDFS(grid, i, j + 1) # right cell
visitIslandDFS(grid, i, j - 1) # left cell
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
numIsland = 0
depth, width = len(grid), len(grid[0])
for i in range(depth):
for j in range(width):
if(grid[i][j] == '1'):
numIsland += 1
visitIslandDFS(grid, i, j)
return numIsland
My question is if we are traversing left to right and top to bottom and flagging off cells to zero, may I know the reason why we are checking left and top cells as well for checks? In other words, I am trying to understand why these two lines are needed?
visitIslandDFS(grid, i - 1, j) # upper cell
visitIslandDFS(grid, i, j - 1) # left cell