Skip to content

Instantly share code, notes, and snippets.

@MattRix
Created December 12, 2021 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattRix/451b5fbad1884221f18bf9c7d3aeef15 to your computer and use it in GitHub Desktop.
Save MattRix/451b5fbad1884221f18bf9c7d3aeef15 to your computer and use it in GitHub Desktop.
Solution for Advent of Code Day 12 that (runs in ~150ms)
var input = File.ReadAllText(Path.GetDirectoryName(Util.CurrentQueryPath) + @"\..\Inputs\aoc_day12.txt");
var lines = input.Split('\n').Select(line=>line.Trim()).ToArray();
var connections = new Dictionary<string,List<string>>();
foreach(var line in lines)
{
var nodeA = line.Split('-')[0];
var nodeB = line.Split('-')[1];
if(!connections.TryGetValue(nodeA, out var listA)) connections[nodeA] = listA = new List<string>();
if(!connections.TryGetValue(nodeB, out var listB)) connections[nodeB] = listB = new List<string>();
listA.Add(nodeB);
listB.Add(nodeA);
}
int numPaths = 0;
var pathNodes = new List<string>();
bool hasUsedTwice = false;
DFS("start");
Console.WriteLine("count: " + numPaths);
void DFS(string node)
{
if(node == "end")
{
numPaths++;
return;
}
if(node == "start" && pathNodes.Count > 0) return;
bool isUpper = char.IsUpper(node[0]);
bool storeUsedTwice = hasUsedTwice;
if(!isUpper && pathNodes.Contains(node))
{
if(hasUsedTwice) return;
else hasUsedTwice = true;
}
pathNodes.Add(node);
foreach(var connection in connections[node]) DFS(connection);
pathNodes.RemoveAt(pathNodes.Count-1);
hasUsedTwice = storeUsedTwice;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment