[DFS&BFS]그래프 노드의 거리와 경로

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Node():
    def __init__(self, node, cnt=None):
        self.node = node
        self.cnt = cnt

def dfs(graph, node):
    global result
    visit.append(node)
    # print(node) 방문 노드 출령
    if node == g:
        result = 1
    for i in graph[node]:
        if i not in visit:
            dfs(graph, i)

def bfs(graph, start, cnt):
    global result
    visit.append(start)
    queue = [Node(start, cnt)]
    while queue:
        current = queue.pop(0)
        if current.node == g:
            result = current.cnt
            break
        for i in graph[current.node]:
            if i not in visit:
                new_cnt = current.cnt + 1
                queue.append(Node(i, new_cnt))
                visit.append(i)


for t in range(int(input())):
    graph = dict()
    v, e = list(map(int, input().split()))
    result = 0
    visit = []

    # Graph initialize
    for i in range(v):
        graph[str(i+1)] = []

    # Links allocated by input value
    for _ in range(e):
        key, val = input().split()
        graph[key].append(val)
        graph[val].append(key)

    s, g = input().split()

    # # BFS 문제일 경우
    # bfs(graph, s, 0)

    # DFS 문제일 경우
    dfs(graph, s)

    print("#{} {}".format(t+1, result))
4871. [파이썬 S/W 문제해결 기본] 4일차 - 그래프 경로 (BFS)
5102. [파이썬 S/W 문제해결 기본] 6일차 - 노드의 거리 (DFS)

댓글

  1. *sample input
    3
    6 5
    1 4
    1 3
    2 3
    2 5
    4 6
    1 6
    7 4
    1 6
    2 3
    2 6
    3 5
    2 5
    9 9
    2 6
    4 7
    5 7
    1 5
    2 9
    3 9
    4 8
    5 3
    7 8
    1 9

    *sample output
    *DFS
    #1 1
    #2 1
    #3 1

    *BFS
    #1 2
    #2 4
    #3 3

    답글삭제

댓글 쓰기

이 블로그의 인기 게시물

[python]섬의 둘레구하기

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

[패턴매칭][Python]보이어 무어 알고리즘