5be796219ea5e98337222745d2695c4ac6ffc6a6
14 struct conn
*connections
;
18 struct node
*get_or_create(struct node
**graph
, char name
[])
21 HASH_FIND_STR(*graph
, name
, n
);
25 n
= malloc(sizeof(struct node
));
27 n
->connections
= NULL
;
28 HASH_ADD_STR(*graph
, key
, n
);
33 void add_connection(struct node
*from
, struct node
*to
)
36 struct conn
*c
= malloc(sizeof(struct conn
));
37 strcpy(c
->key
, to
->key
);
39 HASH_ADD_STR(from
->connections
, key
, c
);
41 c
= malloc(sizeof(struct conn
));
42 strcpy(c
->key
, from
->key
);
44 HASH_ADD_STR(to
->connections
, key
, c
);
47 char **copy_visited(char **visited
, int nvisited
)
49 char **r
= malloc(sizeof(char *)*nvisited
);
50 memcpy(r
, visited
, sizeof(char *)*nvisited
);
54 int find_end(struct node
*node
, char **visited
, int nvisited
, bool twice
)
56 if (strcmp(node
->key
, "end") == 0)
58 if (islower(node
->key
[0])) {
59 for (int i
= 0; i
<nvisited
; i
++)
60 if (strcmp(node
->key
, visited
[i
]) == 0)
62 visited
= realloc(visited
, sizeof(char *)*(nvisited
+1));
63 visited
[nvisited
++] = node
->key
;
66 for (struct conn
*c
= node
->connections
; c
!= NULL
; c
= c
->hh
.next
) {
67 if (twice
&& strcmp(node
->key
, "start") != 0 && islower(node
->key
[0]))
68 r
+= find_end(c
->node
, copy_visited(visited
, nvisited
-1), nvisited
-1, false);
69 r
+= find_end(c
->node
, copy_visited(visited
, nvisited
), nvisited
, twice
);
77 struct node
*graph
= NULL
;
80 while (getline(&buf
, &len
, stdin
) != -1) {
81 char *toname
= strchr(buf
, '-');
83 if (toname
[strlen(toname
)-1] == '\n')
84 toname
[strlen(toname
)-1] = '\0';
85 add_connection(get_or_create(&graph
, buf
),
86 get_or_create(&graph
, toname
));
89 printf("%d\n", find_end(get_or_create(&graph
, "start"), NULL
, 0, true));