<DFS로 구현>
import sys
sys.setrecursionlimit(300000)
input = sys.stdin.readline
n = int(input())
start, end = map(int,input().split())
m = int(input())
graph = [[] for _ in range(n+1)]
graph_dist = [0]*(n+1)
for _ in range(m):
u,v = map(int,input().split())
graph[u].append(v)
graph[v].append(u)
def dfs(start_node):
for i in graph[start_node]:
if graph_dist[i] == 0:
graph_dist[i] = graph_dist[start_node] + 1
dfs(i)
dfs(start)
print(graph_dist[end] if graph_dist[end] > 0 else -1)
<BFS로 구현>
import sys
sys.setrecursionlimit(300000)
input = sys.stdin.readline
from collections import deque
n = int(input())
start, end = map(int,input().split())
m = int(input())
graph = [[] for _ in range(n+1)]
graph_dist = [0]*(n+1)
for _ in range(m):
u,v = map(int,input().split())
graph[u].append(v)
graph[v].append(u)
def bfs(start_node):
q = deque()
q.append(start_node)
while q:
now = q.popleft()
for i in graph[now]:
if graph_dist[i] == 0:
graph_dist[i] = graph_dist[now] + 1
q.append(i)
bfs(start)
print(graph_dist[end] if graph_dist[end] > 0 else -1)
'문제풀이 > 백준(Boj) 문제풀이' 카테고리의 다른 글
[백준][그리디 알고리즘] 20044. Project Teams(파이썬/Python) (0) | 2021.12.27 |
---|---|
[백준][Greedy/BFS] 16953. A → B (파이썬/Python) (0) | 2021.12.27 |
[백준][DFS/BFS] 11725.트리의 부모 찾기 (파이썬/Python) (0) | 2021.12.23 |
[백준][DFS] 6118.숨바꼭질 (파이썬/Python) (0) | 2021.12.21 |
[백준][DFS] 10026. 적록색약 (파이썬/Python) (0) | 2021.12.20 |