Created
April 6, 2026 11:15
-
-
Save maehrm/a1641b8e57aae6a5ab17fd1f134d3a78 to your computer and use it in GitHub Desktop.
E - A Path in A Dictionary https://atcoder.jp/contests/abc417/tasks/abc417_e
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| from collections import deque | |
| sys.setrecursionlimit(10**9) | |
| def can_reach(v, current_visited): | |
| if v == Y: | |
| return True | |
| que = deque([v]) | |
| tmp_visited = current_visited[:] | |
| tmp_visited[v] = True | |
| while que: | |
| u = que.popleft() | |
| for nxt in G[u]: | |
| if nxt == Y: | |
| return True | |
| if tmp_visited[nxt]: | |
| continue | |
| tmp_visited[nxt] = True | |
| que.append(nxt) | |
| return False | |
| def dfs(v, path): | |
| if v == Y: | |
| return True | |
| for nxt in G[v]: | |
| if visited[nxt]: | |
| continue | |
| if not can_reach(nxt, visited): # nxtからYまで到達可能か判断 | |
| continue | |
| visited[nxt] = True | |
| path.append(nxt) | |
| if dfs(nxt, path): | |
| return True | |
| path.pop() | |
| visited[nxt] = False | |
| return False | |
| T = int(input()) | |
| ans = [] | |
| for _ in range(T): | |
| N, M, X, Y = map(int, input().split()) | |
| G = [[] for _ in range(N + 1)] | |
| for _ in range(M): | |
| u, v = map(int, input().split()) | |
| G[u].append(v) | |
| G[v].append(u) | |
| for i in range(1, N + 1): | |
| G[i].sort() | |
| visited = [False] * (N + 1) | |
| visited[X] = True | |
| path = [X] | |
| dfs(X, path) | |
| ans.append(path) | |
| for a in ans: | |
| print(*a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment