Day 12 iterative (not much different from recursive solution)

This commit is contained in:
Stefan Forstenlechner 2021-12-12 13:02:12 +01:00
parent 9d5ad44d26
commit aef252b460
1 changed files with 26 additions and 0 deletions

View File

@ -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<string, ImmutableHashSet<string>> paths, Immutabl
return count;
}
// Part Two iteratively
long count = 0;
var states = new Stack<State>();
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<string> 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<string> visitedSmallCaves, string current, bool twice);
#endif