Skip to content

Instantly share code, notes, and snippets.

@khpatel4991
Created August 29, 2016 03:28
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 khpatel4991/6250733fed91edf7e85321492110a75a to your computer and use it in GitHub Desktop.
Save khpatel4991/6250733fed91edf7e85321492110a75a to your computer and use it in GitHub Desktop.
Find Number of Islands
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