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