Last active
September 26, 2017 05:16
-
-
Save JunKikuchi/9077bebe881d94d5404bb811952da00b 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
data =<<END | |
水土土土土土土土土水水土 | |
土水水水土土土土土水水水 | |
土土土土水水土土土水水土 | |
土土土土土土土土土水水土 | |
土土土土土水土土土水土土 | |
土土水土土土土土土水土土 | |
土水土水土土土土土水水土 | |
水土水土水土土土土土水土 | |
土水土水土土土土土土水土 | |
土土水土土土土土土土水土 | |
END | |
data =<<END | |
土土土土土土土土土土土土 | |
土水土土水土土水水土土土 | |
土水土土水土水土土水土土 | |
土土水水土土水土土水土土 | |
土土土土土土土土土土土土 | |
土水水土土土水水土土水土 | |
土土土水土水土土土水土水 | |
土土土水土水土土土水土水 | |
土水水土土土水水土土水土 | |
土土土土土土土土土土土土 | |
END | |
def dump_ponds(data, ponds) | |
data.split.each_with_index do |row, y| | |
row.each_char.with_index do |c, x| | |
print ponds[[x, y]] || '-' | |
end | |
puts | |
end | |
puts | |
end | |
max = 0 | |
ponds = {} | |
ds = [[-1, 0], [-1, -1], [0, -1], [1, -1]] | |
data.split.each_with_index do |row, y| | |
row.each_char.with_index do |c, x| | |
next unless c == '水' | |
ns = ds.map { |dx, dy| ponds[[x + dx, y + dy]] } | |
ns.delete(nil) | |
if ns.empty? | |
max += 1 | |
ponds[[x, y]] = max | |
else | |
n, *xs = ns | |
xs.each do |x| | |
ponds.each do |pos, val| | |
ponds[pos] = n if val == x | |
end | |
end | |
ponds[[x, y]] = n | |
end | |
# dump_ponds(data, ponds) | |
end | |
end | |
# dump_ponds(data, ponds) | |
p ponds.values.uniq.size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment