From 9f4688d8c0cc18449f4b531802090cf42195643d Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sun, 12 Dec 2021 15:13:41 +0100 Subject: [PATCH] 2021: d12: ex2: add solution --- 2021/d12/ex2/ex2.py | 48 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100755 2021/d12/ex2/ex2.py diff --git a/2021/d12/ex2/ex2.py b/2021/d12/ex2/ex2.py new file mode 100755 index 0000000..86a2c10 --- /dev/null +++ b/2021/d12/ex2/ex2.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python + +import sys +from collections import defaultdict +from typing import Dict, List, Set + +Map = Dict[str, Set[str]] + + +def solve(input: List[str]) -> int: + def parse() -> Map: + res: Map = defaultdict(set) + + for (start, to) in map(lambda s: s.split("-"), input): + res[start].add(to) + res[to].add(start) + + return res + + caves = parse() + + def dfs(start: str, seen: Set[str] = set(), has_doubled_back: bool = False) -> int: + if start == "end": + return 1 + + seen = seen | {start} + res = 0 + + for dest in caves[start]: + doubles_back = False + if dest in seen and dest.islower(): + if has_doubled_back or dest == "start": + continue + doubles_back = True + res += dfs(dest, seen, has_doubled_back or doubles_back) + + return res + + return dfs("start") + + +def main() -> None: + input = [line.strip() for line in sys.stdin.readlines()] + print(solve(input)) + + +if __name__ == "__main__": + main()