-
Notifications
You must be signed in to change notification settings - Fork 3
/
day12.nim
42 lines (31 loc) · 917 Bytes
/
day12.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import strutils, sequtils, tables
const instructions = readFile("./inputs/12.txt").splitLines()
func createGraph(): Table[uint16, seq[uint16]] =
result = initTable[uint16, seq[uint16]]()
for line in instructions:
let
nodes = line.split(" <-> ")
pipe = nodes[0].parseUInt().uint16
result[pipe] = nodes[1].split(", ").mapIt(it.parseUInt().uint16)
let graph = createGraph()
proc dfs(startingPoint: uint16): set[uint16] =
var stack = @[startingPoint]
while stack.len > 0:
let current = stack.pop()
result.incl(current)
for node in graph[current]:
if node notin result:
stack.add(node)
func `+=`(a: var set[uint16], b: set[uint16]) = a = a + b
let firstIsland = dfs(0)
var
groups: uint8
seen: set[uint16]
seen += firstIsland
inc groups
for pipe in graph.keys:
if pipe notin seen:
seen += dfs(pipe)
inc groups
echo firstIsland.card
echo groups