Skip to content

Commit 6c57543

Browse files
Y23 D25
1 parent 8091959 commit 6c57543

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed
+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
using System.Runtime.InteropServices;
2+
3+
namespace AdventOfCode.Puzzles._2023;
4+
5+
[Puzzle(2023, 25, CodeType.Original)]
6+
public partial class Day_25_Original : IPuzzle
7+
{
8+
public (string, string) Solve(PuzzleInput input)
9+
{
10+
var connections = new Dictionary<string, List<string>>();
11+
foreach (var line in input.Lines)
12+
{
13+
var l = line.Split();
14+
var from = l[0][..^1];
15+
16+
foreach (var to in l.Skip(1))
17+
{
18+
connections.GetOrAdd(from, _ => new())
19+
.Add(to);
20+
connections.GetOrAdd(to, to => new())
21+
.Add(from);
22+
}
23+
}
24+
25+
var part1 = 0;
26+
var keys = connections.Keys.ToList();
27+
foreach (var key in keys.Skip(1))
28+
{
29+
var setSize = GetComponentSize(connections, keys[0], key);
30+
if (setSize > 0)
31+
{
32+
part1 = setSize * (keys.Count - setSize);
33+
break;
34+
}
35+
}
36+
37+
return (part1.ToString(), string.Empty);
38+
}
39+
40+
private static int GetComponentSize(
41+
Dictionary<string, List<string>> connections, string start, string end)
42+
{
43+
var flows = new Dictionary<(string from, string to), int>();
44+
var numFlows = 0;
45+
while (true)
46+
{
47+
var componentSize = GetComponentSize(connections, flows, start, end);
48+
if (componentSize == 0)
49+
numFlows++;
50+
else if (numFlows == 3)
51+
return componentSize;
52+
else
53+
break;
54+
}
55+
return 0;
56+
}
57+
58+
private static int GetComponentSize(
59+
Dictionary<string, List<string>> connections,
60+
Dictionary<(string from, string to), int> flows,
61+
string start, string end)
62+
{
63+
var from = new Dictionary<string, string>()
64+
{
65+
[start] = start,
66+
};
67+
68+
var steps = 0;
69+
70+
var queue = new Queue<string>();
71+
queue.Enqueue(start);
72+
73+
while (queue.TryDequeue(out var current) && !from.ContainsKey(end))
74+
{
75+
steps++;
76+
77+
var list = connections[current];
78+
foreach (var dest in connections.Keys)
79+
{
80+
var rate = (list.Contains(dest) ? 1 : 0) - flows.GetValueOrDefault((current, dest));
81+
if (rate > 0 && !from.ContainsKey(dest))
82+
{
83+
from[dest] = current;
84+
queue.Enqueue(dest);
85+
}
86+
}
87+
}
88+
89+
if (!from.ContainsKey(end))
90+
return steps;
91+
92+
var cur = end;
93+
while (cur != start)
94+
{
95+
CollectionsMarshal.GetValueRefOrAddDefault(
96+
flows, (from[cur], cur), out _) += 1;
97+
CollectionsMarshal.GetValueRefOrAddDefault(
98+
flows, (cur, from[cur]), out _) -= 1;
99+
100+
cur = from[cur];
101+
}
102+
103+
return 0;
104+
}
105+
}

0 commit comments

Comments
 (0)