n | def build_adj_mat(input_lines): | n | def get_adj_matrix(lines): |
| adj_mat = {} | | adj_matrix = {} |
| for line in input_lines: | | for line in lines: |
| cave1, cave2 = line.strip().split() | | cave1, cave2 = line.strip().split() |
n | adj_mat.setdefault(cave1, set()).add(cave2) | n | adj_matrix.setdefault(cave1, set()).add(cave2) |
| adj_mat.setdefault(cave2, set()).add(cave1) | | adj_matrix.setdefault(cave2, set()).add(cave1) |
| return adj_mat | | return adj_matrix |
| | | |
n | def can_reach_exit(adj_mat, entrance, exit): | n | def can_reach_exit(adj_matrix, ent, exit): |
| adj_caves = set([entrance]) | | adj_caves = {ent} |
| fl = True | | flag = True |
| while fl: | | while flag: |
| fl = False | | flag = False |
| for cave1 in list(adj_caves): | | for cave1 in list(adj_caves): |
n | for cave2 in adj_mat.get(cave1, []): | n | for cave2 in adj_matrix.get(cave1, []): |
| if cave2 not in adj_caves: | | if cave2 not in adj_caves: |
| adj_caves.add(cave2) | | adj_caves.add(cave2) |
n | fl = True | n | flag = True |
| return exit in adj_caves | | return exit in adj_caves |
n | input_lines = [] | n | lines = [] |
| while True: | | while True: |
| try: | | try: |
| line = input().strip() | | line = input().strip() |
| if not line: | | if not line: |
| break | | break |
n | input_lines.append(line) | n | lines.append(line) |
| except EOFError: | | except EOFError: |
| break | | break |
t | entrance = input_lines[-2] | t | ent = lines[-2] |
| exit = input_lines[-1] | | exit = lines[-1] |
| adj_mat = build_adj_mat(input_lines[:-2]) | | adj_mat = get_adj_matrix(lines[:-2]) |
| if can_reach_exit(adj_mat, entrance, exit): | | if can_reach_exit(adj_mat, ent, exit): |
| print('YES') | | print('YES') |
| else: | | else: |
| print('NO') | | print('NO') |