Created
August 29, 2016 03:28
-
-
Save khpatel4991/6250733fed91edf7e85321492110a75a to your computer and use it in GitHub Desktop.
Find Number of Islands
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
require 'set' | |
# @param {Character[][]} grid | |
# @return {Integer} | |
def num_islands(grid) | |
puts grid.inspect | |
final_count = 0 | |
grid.length.times do |i| | |
grid.length.times do |j| | |
matter = grid[i][j] | |
if land?(matter) && !surrounding_set(grid, i, j).member? '1' | |
final_count += 1 | |
end | |
end | |
end | |
final_count | |
end | |
def land?(matter) | |
matter == '1' | |
end | |
def surrounding_set(a, i, j) | |
set = Set.new | |
set.add a.fetch [i-1][j], '0' #Top | |
set.add a.fetch [i+1][j], '0' #Bottom | |
set.add a.fetch [i][j+1], '0' #Right | |
set.add a.fetch [i+1][j], '0' #Left | |
set | |
end | |
num_islands %w(%w(1 0 0) %w(1 0 0) %w(1 0 1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment