Created
April 26, 2016 01:54
-
-
Save timurcatakli/4eb8beb524686d39162a2706d29a23e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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