[DFS][Python]Finding Path from start to goal in graph

 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번 문제

댓글

  1. 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/

    답글삭제

댓글 쓰기

이 블로그의 인기 게시물

[python]섬의 둘레구하기

백트래킹으로 부분집합구하기(Get Powerset usiing Backtracking)

[Python]DFS를 이용한 부분집합 구현