Here is the solution:
function eraseIsland(grid, r, c):
if r < 0 or c < 0 or r >= rows or c >= cols:
return
if grid[r][c] == '0':
return
grid[r][c] = '0' // Sink it
eraseIsland(grid, r + 1, c)
eraseIsland(grid, r - 1, c)
eraseIsland(grid, r, c + 1)
eraseIsland(grid, r, c - 1)
function numIslands(grid):
count = 0
for i from 0 to rows - 1:
for j from 0 to cols - 1:
if grid[i][j] == '1':
count = count + 1
eraseIsland(grid, i, j)
return count
This runs in time and uses space.