You are given an n x n grid represented as a list of lists, where each cell is either 1 (land) or 0 (water). An island is a group of 1s connected horizontally or vertically (4-directional adjacency). Diagonal connections do not count.
Write a function count_islands(grid) that returns the number of distinct islands in the grid. If the grid is empty, return 0.