diff --git a/Day12.cs b/Day12.cs index 6360dfd..ce7a158 100644 --- a/Day12.cs +++ b/Day12.cs @@ -1,6 +1,7 @@ #define Day12 #if Day12 using System.Collections.Immutable; +using System.Diagnostics; using AoC2021; const string START = "start"; const string END = "end"; @@ -65,4 +66,29 @@ long PathCountPart2(Dictionary> paths, Immutabl return count; } + +// Part Two iteratively +long count = 0; +var states = new Stack(); +states.Push(new State(ImmutableHashSet.Create(START), START, false)); +while (states.Count > 0) { + var s = states.Pop(); + count += paths[s.current].Contains(END) ? 1 : 0; + ImmutableHashSet adjacent; + if (s.twice) { + adjacent = paths[s.current].Except(s.visitedSmallCaves).Remove(END); + } else { + adjacent = paths[s.current].Remove(END); + } + foreach (var a in adjacent) { + if (Char.IsLower(a[0])) { + states.Push(new State(s.visitedSmallCaves.Add(a), a, s.twice || s.visitedSmallCaves.Contains(a))); + } else { + states.Push(new State(s.visitedSmallCaves, a, s.twice)); + } + } +} +Console.WriteLine(count); + +record State(ImmutableHashSet visitedSmallCaves, string current, bool twice); #endif \ No newline at end of file