|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import numpy |
| 4 | +from collections import deque |
| 5 | + |
| 6 | + |
| 7 | +class Map: |
| 8 | + def __init__(self, max_x, max_y, max_z): |
| 9 | + self.size_x = max_x + 3 |
| 10 | + self.size_y = max_y + 3 |
| 11 | + self.size_z = max_z + 3 |
| 12 | + self.map = numpy.zeros((self.size_x, self.size_y, self.size_z), dtype=numpy.uint8) |
| 13 | + |
| 14 | + def flood_fill(self): |
| 15 | + queue = deque([[0, 0, 0]]) |
| 16 | + while len(queue) > 0: |
| 17 | + cell = queue.popleft() |
| 18 | + if self.map[cell[0], cell[1], cell[2]] != 0: |
| 19 | + continue |
| 20 | + |
| 21 | + self.map[cell[0], cell[1], cell[2]] = 2 |
| 22 | + |
| 23 | + if cell[0] > 0 and self.map[cell[0] - 1, cell[1], cell[2]] == 0: |
| 24 | + queue.append([cell[0] - 1, cell[1], cell[2]]) |
| 25 | + if cell[0] < self.size_x - 1 and self.map[cell[0] + 1, cell[1], cell[2]] == 0: |
| 26 | + queue.append([cell[0] + 1, cell[1], cell[2]]) |
| 27 | + if cell[1] > 0 and self.map[cell[0], cell[1] - 1, cell[2]] == 0: |
| 28 | + queue.append([cell[0], cell[1] - 1, cell[2]]) |
| 29 | + if cell[1] < self.size_y - 1 and self.map[cell[0], cell[1] + 1, cell[2]] == 0: |
| 30 | + queue.append([cell[0], cell[1] + 1, cell[2]]) |
| 31 | + if cell[2] > 0 and self.map[cell[0], cell[1], cell[2] - 1] == 0: |
| 32 | + queue.append([cell[0], cell[1], cell[2] - 1]) |
| 33 | + if cell[2] < self.size_z - 1 and self.map[cell[0], cell[1], cell[2] + 1] == 0: |
| 34 | + queue.append([cell[0], cell[1], cell[2] + 1]) |
| 35 | + |
| 36 | + |
| 37 | + def count_exposed_faces(self): |
| 38 | + count = 0 |
| 39 | + for x in range(self.size_x): |
| 40 | + for y in range(self.size_y): |
| 41 | + for z in range(self.size_z): |
| 42 | + if self.map[x, y, z] == 1: |
| 43 | + if x == 0 or self.map[x - 1, y, z] == 2: |
| 44 | + count += 1 |
| 45 | + if x == self.size_x - 1 or self.map[x + 1, y, z] == 2: |
| 46 | + count += 1 |
| 47 | + if y == 0 or self.map[x, y - 1, z] == 2: |
| 48 | + count += 1 |
| 49 | + if y == self.size_y - 1 or self.map[x, y + 1, z] == 2: |
| 50 | + count += 1 |
| 51 | + if z == 0 or self.map[x, y, z - 1] == 2: |
| 52 | + count += 1 |
| 53 | + if z == self.size_z - 1 or self.map[x, y, z + 1] == 2: |
| 54 | + count += 1 |
| 55 | + return count |
| 56 | + |
| 57 | + |
| 58 | +lines = [list(map(lambda c: int(c), line.strip().split(","))) for line in open('18.input').readlines()] |
| 59 | + |
| 60 | +max_x = max([x for x, _, _ in lines]) |
| 61 | +max_y = max([y for _, y, _ in lines]) |
| 62 | +max_z = max([z for _, _, z in lines]) |
| 63 | + |
| 64 | +obj = Map(max_x, max_y, max_z) |
| 65 | + |
| 66 | +for coords in lines: |
| 67 | + obj.map[coords[0], coords[1], coords[2]] = 1 |
| 68 | + |
| 69 | +obj.flood_fill() |
| 70 | +print(obj.count_exposed_faces()) |
0 commit comments