Skip to content

Instantly share code, notes, and snippets.

@tokoroten
Created September 15, 2013 14:13
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 tokoroten/6571100 to your computer and use it in GitHub Desktop.
Save tokoroten/6571100 to your computer and use it in GitHub Desktop.
#coding: utf-8
#python 2.7
class island_count:
def __init__(self, pattern = None):
self.pattern = None
if pattern:
self.load(pattern)
def load(self, pattern):
self.pattern = [list(linedata) for linedata in pattern.splitlines()]
#for items in self.pattern:
# print " ".join(items)
w_max = max(map(len, self.pattern))
w_min = min(map(len, self.pattern))
if w_max != w_min:
raise "invalid width"
self.width = w_max
self.height = len(self.pattern)
def count(self):
if not self.pattern:
return -1
already_read = set()
def step(x, y):
if (x,y) in already_read:
return False
if self.pattern[y][x] == u"●":
already_read.add((x,y))
if x > 0:
step(x - 1, y)
if y > 0:
step(x, y - 1)
if x < self.width - 1:
step(x + 1, y)
if x > self.height - 1:
step(x, y + 1)
return True
else:
return False
c = 0
for y in xrange(self.height):
for x in xrange(self.width):
if step(x,y):
c += 1
return c
def main():
pattern = u"""○○○○○○
○●●○○○
○○○○○○
○○○○●○
○○○●○○
○○○○○○
"""
island = island_count()
island.load(pattern)
print island.count()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment