Skip to content
advent of code 2019

day 03

crossed wires

approach

each wire is walked one unit step at a time. used returns a dict from every (x, y) the wire visits to the number of steps it took to get there the first time.

part 1 intersects the key sets of both wires and takes the smallest manhattan distance from the origin. part 2 uses the same intersection but sums the two step counts at each crossing and takes the minimum.

the trick

record only the first visit to each cell, so the dict gives part 2's step counts for free.

python
for ins in w.split(","):
    d,n=ins[0],int(ins[1:])
    for _ in range(n):
        xoff,yoff=step[d]
        x,y,c=(x+xoff,y+yoff,c+1)
        if (x,y) not in s:
            s[(x,y)]=c