Skip to content

Commit 67150a9

Browse files
committed
200
1 parent 6cb8918 commit 67150a9

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

ruby/200-Number-of-Islands.rb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
DIRS = [[0, 1], [0, -1], [1, 0], [-1, 0]].freeze
2+
3+
def num_islands(grid)
4+
islands = 0
5+
memo = Array.new(grid.length) { Array.new(grid[0].length) }
6+
grid.each_with_index do |row, y|
7+
row.each_with_index do |el, x|
8+
if memo[y][x].nil? && el == '1'
9+
islands += 1
10+
flood_fill(grid, memo, y, x)
11+
end
12+
end
13+
end
14+
islands
15+
end
16+
17+
def flood_fill(grid, memo, y, x)
18+
return nil if y >= grid.length || y.negative? ||
19+
x >= grid[0].length || x.negative? ||
20+
memo[y][x] != nil ||
21+
grid[y][x] == '0'
22+
23+
memo[y][x] = true
24+
DIRS.each do |dy, dx|
25+
dy += y
26+
dx += x
27+
flood_fill(grid, memo, dy, dx)
28+
end
29+
end

0 commit comments

Comments
 (0)