-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathday20.py
125 lines (107 loc) · 2.6 KB
/
day20.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#!/usr/bin/env python
import sys, itertools, collections
regex = raw_input()
regex = regex[1:-1]
i = 0
def peek():
if i < len(regex):
return regex[i]
else:
return None
def get():
global i
c = regex[i]
i += 1
return c
Sequence = collections.namedtuple('Sequence', 'seq')
Alternative = collections.namedtuple('Alternative', 'alts')
Literal = collections.namedtuple('Literal', 'dir')
def parse_expr():
seq = []
while peek() is not None and peek() in 'NESW(':
if peek() == '(':
seq.append(parse_alt())
else:
seq.append(Literal(get()))
return Sequence(seq)
def parse_alt():
assert get() == '('
alts = []
while True:
alts.append(parse_expr())
c = get()
if c == ')':
break
assert c == '|'
return Alternative(alts)
class State(object):
def __init__(self):
self.successors = []
allstates = []
def traverse(expr, start):
current = start
for e in expr.seq:
end = State()
if isinstance(e, Alternative):
for a in e.alts:
next = traverse(a, current)
next.successors.append((None,end))
elif isinstance(e, Literal):
current.successors.append((e.dir,end))
current = end
return current
"""next_num = 0
visited = set([])
def number(node):
global next_num
if node in visited:
return
visited.add(node)
for _, next in node.successors:
number(next)
node.index = next_num
next_num += 1"""
visited = set([])
edges = collections.defaultdict(set)
head = State()
traverse(parse_expr(), head)
stack = [(0,0,head)]
deltas = {'N': (0,1), 'E': (1,0), 'S': (0,-1), 'W': (-1,0)}
while stack:
current = stack.pop()
if current in visited:
continue
visited.add(current)
x, y, curstate = current
for dir, nextstate in curstate.successors:
if dir is not None:
dx, dy = deltas[dir]
x2 = x+dx
y2 = y+dy
edges[x,y].add((x2,y2))
edges[x2,y2].add((x,y))
else:
x2 = x
y2 = y
stack.append((x2, y2, nextstate))
for k in sorted(edges):
print k, edges[k]
visited = set([])
queue = [(0,0)]
dist = 0
far = 0
while queue:
print queue
nextqueue = []
for cur in queue:
if cur in visited:
continue
visited.add(cur)
if dist >= 1000:
far += 1
for next in edges[cur]:
nextqueue.append(next)
queue = nextqueue
dist += 1
print dist - 2
print far, "out of", len(edges)