깊이 우선 탐색 3번과 동일한 문제로 스택에 내림차순으로 연결 노드를 방문하는 데 주의.
import sys
from collections import deque
n, m, r = map(int, sys.stdin.readline().rstrip().split())
nodes = [[] for _ in range(n+1)]
visited = [False for _ in range(n+1)]
nodes_depth = [0 for _ in range(n+1)]
for _ in range(m):
tail, head = map(int, sys.stdin.readline().rstrip().split())
nodes[tail].append(head)
nodes[head].append(tail)
for i in range(n+1):
nodes[i].sort()
stack = deque()
stack.append([r, 0])
while stack:
cur_node, depth = stack.pop()
if visited[cur_node]: continue
visited[cur_node] = True
nodes_depth[cur_node] = depth
for next_node in nodes[cur_node]:
if not visited[next_node]:
stack.append([next_node, depth+1])
for i in range(1, n+1):
if i == r: print(0)
elif nodes_depth[i] == 0: print(-1)
else: print(nodes_depth[i])