cat fixtures | python3 floodfill.py
Last active
November 9, 2017 17:22
-
-
Save padawin/0ac7a55e530dc018c72e5e942d3f49b6 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
4 | |
4 | |
1100 | |
0110 | |
0010 | |
1000 |
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
# Input | |
# 4 | |
# 4 | |
# 1100 | |
# 0110 | |
# 0010 | |
# 1000 | |
class GridAnalyser(object): | |
def __init__(self): | |
self.tmp_count, self.max_count = 0, 0 | |
def analyse_grid(self, grid): | |
for y in range(grid.height): | |
for x in range(grid.width): | |
self.tmp_count = 0 | |
grid.fill(x, y, self) | |
self.max_count = max(self.max_count, self.tmp_count) | |
class Grid(object): | |
def __init__(self, width, height): | |
self.width, self.height = width, height | |
self.grid = [] | |
for y in range(self.height): | |
line = [] | |
for x in range(self.width): | |
line.append(0) | |
self.grid.append(line) | |
def set(self, x, y, val): | |
self.grid[y][x] = val | |
def fill(self, x, y, analyser): | |
if x < 0 or y < 0 or x >= self.width or y >= self.height: | |
return | |
# out of the zone to fill | |
if self.grid[y][x] != 1: | |
return | |
self.grid[y][x] = 2 | |
analyser.tmp_count += 1 | |
self.fill(x - 1, y, analyser) | |
self.fill(x + 1, y, analyser) | |
self.fill(x, y - 1, analyser) | |
self.fill(x, y + 1, analyser) | |
# Diagonals | |
self.fill(x - 1, y - 1, analyser) | |
self.fill(x + 1, y - 1, analyser) | |
self.fill(x - 1, y + 1, analyser) | |
self.fill(x + 1, y + 1, analyser) | |
def main(): | |
height, width = int(input()), int(input()) | |
grid = Grid(width, height) | |
for y in range(height): | |
line = input().strip() | |
for x in range(width): | |
grid.set(x, y, int(line[x])) | |
analyser = GridAnalyser() | |
analyser.analyse_grid(grid) | |
print(analyser.max_count) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment