10 bool debug(const char *fmt
, ...) {
12 if (getenv("DEBUG")) {
14 vfprintf(stderr
, fmt
, ap
);
21 char visit(int depth
, char end
, int *score
) {
23 debug("depth %d, visiting %c while looking for %c, score %d\n",
24 depth
, c
, end
, *score
);
26 case 'N': case 'E': case 'S': case 'W':
28 return visit(depth
, end
, score
);
30 if (end
!= c
|| depth
!= 0) {
31 fprintf(stderr
, "unbalanced regex\n");
39 c
= visit(depth
+ 1, '|', &best
);
40 assert(c
== '|' && best
);
41 while (visit(depth
+ 1, ')', &tmp
) == '|') {
51 return visit(depth
, end
, score
);
53 debug("checking after empty alternation at depth %d\n", depth
);
54 best
= *score
+ best
/ 2;
55 c
= visit(depth
, end
, score
);
61 if (end
!= ')' && end
!= c
) {
62 fprintf(stderr
, "unbalanced regex\n");
67 fprintf(stderr
, "unexpected EOF\n");
72 int main(int argc
, char **argv
) {
75 if (argc
> 1 && !(stdin
= freopen(argv
[1], "r", stdin
))) {
79 if (getchar() != '^') {
80 fprintf(stderr
, "invalid start\n");
83 visit(0, '$', &score
);
84 printf("Furthest point is %d doors away\n", score
);