Explain how you would determine the number of islands in a 2D grid using graph traversal techniques.
Implement num_islands(grid), where grid is a list of lists containing 1 for land and 0 for water. Return the number of islands, where land cells are connected only horizontally or vertically. You may modify grid during traversal.
def num_islands(grid):