How would you solve the number of islands problem in a matrix?
Implement the function below. The matrix contains '1' for land and '0' for water. An island consists of horizontally or vertically adjacent land cells, and the function should return the number of distinct islands.
Use the function signature and input/output shapes specified below. You may mutate the matrix during traversal.
def num_islands(grid):