1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 | def dfs(graph, start):
visited, stack = [], [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.append(vertex)
stack += graph[vertex] - set(visited)
return visited
for t in range(int(input())):
graph = dict()
v, e = list(map(int, input().split()))
# Graph initialize
for i in range(v):
graph[str(i+1)] = set()
# Links allocated by input value
for _ in range(e):
key, val = input().split()
graph[key].add(val)
s, g = input().split()
vtd = dfs(graph, s)
if g in vtd:
result = 1
else:
result = 0
print("#{} {}".format(t+1, result))
|
참고문제: SW Expert Academy 4871번 문제
reference
답글삭제http://ejklike.github.io/2018/01/05/bfs-and-dfs.html
https://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/