day12: go even faster

This commit is contained in:
Stefan Harmuth 2021-12-12 07:50:58 +01:00
parent 9a327ec92a
commit 03f0491671

View File

@ -12,29 +12,27 @@ def getCaveMap(lines: List[List[str]]) -> Dict[str, List[str]]:
return m return m
def getPaths(caveMap: Dict[str, List[str]], start: str, visited: set, noDouble: bool = True) -> List[List[str]]: def getPaths(caveMap: Dict[str, List[str]], start: str, visited: set, noDouble: bool = True) -> int:
paths = [] pathCount = 0
visited.add(start) visited.add(start)
for thisCave in caveMap[start]: for thisCave in caveMap[start]:
if thisCave == 'start': if thisCave == 'start':
continue continue
if thisCave == 'end': if thisCave == 'end':
paths.append(['end']) pathCount += 1
continue continue
foundDouble = False foundDouble = False
if thisCave.islower() and thisCave in visited: if thisCave.islower() and thisCave in visited:
if noDouble: if noDouble:
continue continue
foundDouble = True foundDouble = True
sub_paths = getPaths(caveMap, thisCave, visited.copy(), noDouble or foundDouble) pathCount += getPaths(caveMap, thisCave, visited.copy(), noDouble or foundDouble)
for x in sub_paths:
if 'end' in x:
paths.append(x)
return paths return pathCount
class Day(AOCDay): class Day(AOCDay):
@ -43,8 +41,8 @@ class Day(AOCDay):
def part1(self) -> Any: def part1(self) -> Any:
caveMap = getCaveMap(self.getInputAsArraySplit("-")) caveMap = getCaveMap(self.getInputAsArraySplit("-"))
return len(getPaths(caveMap, 'start', set())) return getPaths(caveMap, 'start', set())
def part2(self) -> Any: def part2(self) -> Any:
caveMap = getCaveMap(self.getInputAsArraySplit("-")) caveMap = getCaveMap(self.getInputAsArraySplit("-"))
return len(getPaths(caveMap, 'start', set(), False)) return getPaths(caveMap, 'start', set(), False)