Given a 2D grid representing land (1) and water (0), calculate the total number of islands using DFS or BFS.
Implement num_islands(grid), where adjacent land cells are connected horizontally or vertically, but not diagonally. Return the number of distinct islands. The function may modify the input grid while marking visited land cells.
grid is a rectangular list of lists containing only 0 and 1. Return an integer count.
def num_islands(grid):