From d4524174ccd9d78233690936f5dde7a70c7c74a4 Mon Sep 17 00:00:00 2001 From: Maciej Jur Date: Sun, 12 Dec 2021 12:57:30 +0100 Subject: [PATCH] [2021] day 12 python --- 2021/.input/day12 | 23 +++++++++++++++++++++ 2021/Python/day12.py | 48 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 2021/.input/day12 create mode 100644 2021/Python/day12.py diff --git a/2021/.input/day12 b/2021/.input/day12 new file mode 100644 index 0000000..1c0b034 --- /dev/null +++ b/2021/.input/day12 @@ -0,0 +1,23 @@ +start-YA +ps-yq +zt-mu +JS-yi +yq-VJ +QT-ps +start-yq +YA-yi +start-nf +nf-YA +nf-JS +JS-ez +yq-JS +ps-JS +ps-yi +yq-nf +QT-yi +end-QT +nf-yi +zt-QT +end-ez +yq-YA +end-JS \ No newline at end of file diff --git a/2021/Python/day12.py b/2021/Python/day12.py new file mode 100644 index 0000000..d3e5194 --- /dev/null +++ b/2021/Python/day12.py @@ -0,0 +1,48 @@ +import re + + +input_pattern = re.compile(r'([a-zA-Z]+)-([a-zA-Z]+)') +small_pattern = re.compile(r'([a-z]+)') + + +def load(): + with open('../.input/day12', 'r') as f: + return input_pattern.findall(f.read()) + + +def construct_paths(graph, start, end, path=None, single_reentry=False): + if path is None: + path = [start] + + if start == end: + yield path + else: + for node in graph[start]: + is_small = small_pattern.match(node) + if not is_small or node not in path: + yield from construct_paths(graph, node, end, path + [node], single_reentry) + elif is_small and single_reentry and node not in ["start", "end"]: + yield from construct_paths(graph, node, end, path + [node]) + + +def solve1(): + graph = {} + for node1, node2 in load(): + graph.setdefault(node1, set()).add(node2) + graph.setdefault(node2, set()).add(node1) + + return sum(1 for _ in construct_paths(graph, 'start', 'end')) + + +def solve2(): + graph = {} + for node1, node2 in load(): + graph.setdefault(node1, set()).add(node2) + graph.setdefault(node2, set()).add(node1) + + return sum(1 for _ in construct_paths(graph, 'start', 'end', single_reentry=True)) + + +if __name__ == '__main__': + print(solve1()) # 4304 + print(solve2()) # 118242