[백준 24480] 알고리즘 수업 - 깊이 우선 탐색 2

Junyoung Park·2022년 3월 2일
0

코딩테스트

목록 보기
151/631
post-thumbnail

1. 문제 설명

알고리즘 수업 - 깊이 우선 탐색 2

2. 문제 분석

이전과 스택에 연결 노드를 넣는 순서만 다르다. (내림차순 또는 오름차순)

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_cnt = [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()
cnt = 1
# def DFS(cur_node):
#     global cnt
#     visited[cur_node] = True
#     if nodes_cnt[cur_node] == 0:
#         nodes_cnt[cur_node] = cnt
#         cnt += 1
#     for next_node in nodes[cur_node]:
#         if not visited[next_node]:
#             DFS(next_node)

# DFS(r)

stack = deque()
stack.append(r)

while stack:
    cur_node = stack.pop()
    visited[cur_node] = True
    if nodes_cnt[cur_node] == 0:
        nodes_cnt[cur_node] = cnt
        cnt += 1

    for next_node in nodes[cur_node]:
        if not visited[next_node]:
            stack.append(next_node)


for cnt in nodes_cnt[1:]:
    print(cnt)
profile
JUST DO IT

0개의 댓글