Skip to content

Instantly share code, notes, and snippets.

@timurcatakli
Created April 26, 2016 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timurcatakli/4eb8beb524686d39162a2706d29a23e6 to your computer and use it in GitHub Desktop.
Save timurcatakli/4eb8beb524686d39162a2706d29a23e6 to your computer and use it in GitHub Desktop.
def num_islands(grid)
return 0 if not grid
result = 0
grid.length.times do |i|
grid[0].length.times do |j|
if grid[i][j] == 1
result += 1
extend(grid,i,j)
end
end
end
result
end
def extend(grid,i,j)
if i < grid.length and j < grid[0].length and i >= 0 and j >= 0 and grid[i][j] == 1
grid[i][j] = 0
extend(grid,i+1,j)
extend(grid,i,j+1)
extend(grid,i-1,j)
extend(grid,i,j-1)
extend(grid,i-1,j-1)
extend(grid,i-1,j+1)
extend(grid,i+1,j-1)
extend(grid,i+1,j+1)
end
end
grid = [
[1,1,0,0,0],
[0,1,0,0,1],
[1,0,0,1,1],
[0,0,0,0,0],
[1,0,1,0,1] ]
print num_islands(grid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment