data = open('input', 'r').readlines() data = [list(x.strip()) for x in data] def neighbors(mat, x, y): height = len(mat) width = len(mat[0]) for i in range(3): for j in range(3): dx = i - 1 dy = j - 1 if dx == 0 and dy == 0: continue if x + dx < 0 or y + dy < 0: continue if x + dx >= height or y + dy >= width: continue yield data[x + dx][y+dy] def serialize(mat): return '\n'.join([''.join(line) for line in mat]) def apply(mat): newData = [] for x, _ in enumerate(mat): line = [] for y, _ in enumerate(mat[x]): neigh = list(neighbors(mat, x, y)) if mat[x][y] == 'L' and '#' not in neigh: line.append('#') elif mat[x][y] == '#' and neigh.count('#') >= 4: line.append('L') else: line.append(mat[x][y]) newData.append(line) return newData prev = '' while serialize(data) != prev: prev = serialize(data) data = apply(data) # print(serialize(data)) print(prev.count('#'))