DFS/BFS
์ธ ๋ฒ์งธ ๋ฌธ์ !
์์ง๊น์ง dfs
์ ๊ฐ๋จํ ๊ตฌํ ๋ฌธ์ ๋ผ ์ด๋ ต์ง ์๋ค.
def dfs(start_node, cnt, visit = list()):
visit.append(start_node)
if start_node == d2:
print(cnt)
global check
check = 1
for x in graph[start_node]:
if x not in visit:
dfs(x, cnt+1, visit)
# input
people = int(input())
d1, d2 = map(int, input().split())
graph = dict()
n = int(input())
for _ in range(n):
x, y = map(int, input().split())
if x in graph:
graph[x].append(y)
else:
graph[x] = [y]
if y in graph:
graph[y].append(x)
else:
graph[y] = [x]
global check
check = 0
# output
dfs(d1, 0)
if check == 0:
print(-1)
์ด๋ ค์ ๋ ์ ์ ์์ธ ์ฒ๋ฆฌ์๋ค.
๋ค๋ฅธ ๋ฐฉ๋ฒ์ด ๋ ์ค๋ฅด์ง ์์, global
๋ณ์๋ฅผ ์ ์ธํด์ ์ฒ๋ฆฌํ๋ค.
from collections import deque
import sys
input = sys.stdin.readline
n = int(input())
a, b = map(int, input().split())
m = int(input())
s = [[] for i in range(n + 1)]
result = [0 for i in range(n + 1)]
def bfs(start):
q = deque()
q.append(start)
visit = [0 for i in range(n + 1)]
visit[start] = 1
while q:
d = q.popleft()
for i in s[d]:
if visit[i] == 0:
visit[i] = 1
result[i] = result[d] + 1
q.append(i)
for i in range(m):
x, y = map(int, input().split())
s[x].append(y)
s[y].append(x)
bfs(a)
print(result[b] if result[b] != 0 else -1)
double-list
๋ก graph
๋ฅผ ๊ตฌ์ฑํ์
จ๋ค.
์์ธ ์ฒ๋ฆฌ ๋ถ๋ถ์ด ์ฐธ์ ํ๋ค.
๋ณ๋์ list
๋ก ์ฒ๋ฆฌํ์
จ๋๋ฐ, ๋ด๊ฐ ์ ์๊ฐํ์ง ๋ชปํ๋ ๋ฐฉ์์ด๋ค.