···11+import fileinput
22+from collections import defaultdict
33+from utils import Point, DIRS_4
44+55+66+REGEX = fileinput.input()[0].strip().replace('$', '').replace('^', '')
77+DIRS = {a: b for a, b in zip('NESW', DIRS_4)}
88+99+# Build graph of facility
1010+graph = defaultdict(set)
1111+start = Point(0, 0)
1212+curr = start
1313+stk = []
1414+1515+for d in REGEX:
1616+ if d in DIRS:
1717+ nx = curr + DIRS[d]
1818+ graph[curr].add(nx)
1919+ graph[nx].add(curr)
2020+ curr = nx
2121+ elif d == '(':
2222+ stk.append(curr)
2323+ elif d == '|':
2424+ curr = stk[-1]
2525+ elif d == ')':
2626+ curr = stk.pop()
2727+2828+seen = set()
2929+horizon = [start]
3030+dist = {}
3131+3232+# BFS to solve for minimum distances to rooms
3333+depth = 0
3434+while horizon:
3535+ next_horizon = []
3636+3737+ for h in horizon:
3838+ if h in seen:
3939+ continue
4040+4141+ dist[h] = depth
4242+ seen.add(h)
4343+4444+ for g in graph[h]:
4545+ next_horizon.append(g)
4646+4747+ depth += 1
4848+ horizon = next_horizon
4949+5050+5151+print "Largest number of doors passed through:", max(d for d in dist.values())
5252+print "Rooms passing through at least 1000 doors:", sum(d >= 1000 for d in dist.values())