The problem is this Qiita 13th Offline Real-Time Writing Problem I solved it with Python. I saw a problem in the morning and wondered if that would be good during work. Implementation takes about 1 hour.
doukaku_13.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def create_aquarium(input):
#0 is an empty space,1 is a square with building blocks
aquarium = []
for num in input:
brick_line = [0 for i in range(9)]
for i in range(int(num)):
brick_line[8 - i] = 1
aquarium.append(brick_line)
aquarium.append([0 for i in range(9)])
aquarium.insert(0, [0 for i in range(9)])
return aquarium
def fill_air(aquarium):
#Breadth-first search
def fill(y, x):
aquarium[y][x] = 2
try:
if aquarium[y + 1][x] == 0: fills.append((y + 1, x))
except: pass
try:
if aquarium[y - 1][x] == 0: fills.append((y - 1, x))
except: pass
try:
if aquarium[y][x - 1] == 0: fills.append((y, x - 1))
except: pass
fills = []
#setup
for i in range(len(aquarium)):
if aquarium[i][8] == 0:
fills.append((i, 8))
for y, x in fills:
fill(y, x)
return aquarium
def count_water(aquarium):
return sum([line.count(0) for line in aquarium])
def test(input, answer):
aquarium = fill_air(create_aquarium(input))
my_answer = str(count_water(aquarium))
if my_answer == answer:
return True
else:
print "answer is %s but my answer is %s" % (answer, my_answer)
if __name__ == "__main__":
test( "83141310145169154671122", "24" )
test( "923111128", "45" )
test( "923101128", "1" )
test( "903111128", "9" )
test( "3", "0" )
test( "31", "0" )
test( "412", "1" )
test( "3124", "3" )
test( "11111", "0" )
test( "222111", "0" )
test( "335544", "0" )
test( "1223455321", "0" )
test( "000", "0" )
test( "000100020003121", "1" )
test( "1213141516171819181716151413121", "56" )
test( "712131415161718191817161514131216", "117" )
test( "712131405161718191817161514031216", "64" )
test( "03205301204342100", "1" )
test( "0912830485711120342", "18" )
test( "1113241120998943327631001", "20" )
test( "7688167781598943035023813337019904732", "41" )
test( "2032075902729233234129146823006063388", "79" )
test( "8323636570846582397534533", "44" )
test( "2142555257761672319599209190604843", "41" )
test( "06424633785085474133925235", "51" )
test( "503144400846933212134", "21" )
test( "1204706243676306476295999864", "21" )
test( "050527640248767717738306306596466224", "29" )
test( "5926294098216193922825", "65" )
test( "655589141599534035", "29" )
test( "7411279689677738", "34" )
test( "268131111165754619136819109839402", "102" )
Rather than looking for a square that collects water, I solved it as if I were looking for a square that does not collect water. Search from the bottom to the top of the field, and when you finish searching to the top, water will collect in the unsearched squares.
Recommended Posts