반응형
간단하게 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 | n = int(input()) a, b = map(int, input().split()) m = int(input()) arr = list([0]*(n) for i in range(n)) v = list([0]*(n)) def bfs(x) : que = [x] while que : cur = que.pop(0) for i in range(n) : if arr[cur][i] == 1 and v[i] == 0 : v[i] = v[cur] + 1 que.append(i) for i in range(m) : x, y = map(int, input().split()) arr[x-1][y-1] = arr[y-1][x-1] = 1 bfs(a-1) print(v[b-1] if v[b-1] else -1) | cs |
반응형
'0 > algorithm' 카테고리의 다른 글
백준 7576번 토마토 (Python) (0) | 2018.11.11 |
---|---|
Kickstart Round A 2018 Problem A (0) | 2018.11.11 |
백준 3273번 두수의 합 (Python) (0) | 2018.11.02 |
백준 11501번 주식 (Python) (0) | 2018.11.02 |
백준 2042번 구간 합 (Python) (1) | 2018.11.02 |