[BOJ] 13023๋ฒˆ: ABCDE (Python) (+ 1260๋ฒˆ)

seulzzangยท2022๋…„ 12์›” 15์ผ
0

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต

๋ชฉ๋ก ๋ณด๊ธฐ
42/44
post-thumbnail


๋จผ์ € 13023๋ฒˆ์„ ํ’€๊ธฐ ์ „์— 1260๋ฒˆ ํ’€์ด๋ฅผ ์ฒจ๋ถ€ํ•œ๋‹ค!
DFS์™€ BFS๋ฅผ ๊ตฌํ˜„ํ•˜์—ฌ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

# DFS์™€ BFS
import sys
from collections import deque

input = sys.stdin.readline

N, M, V = map(int, input().split())
graph = [[] for _ in range(N+1)]
visited = [0] * (N+1) # dfs
visited2 = [0] * (N+1) # bfs

for i in range(M):
    a, b = map(int, input().split())
    graph[a].append(b)
    graph[b].append(a)

# ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ •์ ์ด ์—ฌ๋Ÿฌ๊ฐœ์ธ ๊ฒฝ์šฐ ์ •์  ๋ฒˆํ˜ธ๊ฐ€ ์ž‘์€ ๊ฒƒ์„ ๋จผ์ € ๋ฐฉ๋ฌธํ•œ๋‹ค
for i in graph:
    i.sort()
# print(graph)

def dfs(graph, start, visited):
    visited[start] = True
    print(start, end=' ')
    for i in graph[start]:
        if not visited[i]:
            dfs(graph, i, visited)

def bfs(graph, start, visited):
    q = deque([start])
    visited[start] = True
    while q:
        v = q.popleft()
        print(v, end=' ')
        for i in graph[v]:
            if not visited[i]:
                q.append(i)
                visited[i] = True

dfs(graph, V, visited)
print()
bfs(graph, V, visited2)

๐Ÿ“๋ฌธ์ œ

[BOJ] 13023๋ฒˆ: ABCDE

๐Ÿ’ป๋‚˜์˜ ํ’€์ด

์˜ค๋Š˜์€ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์นœ๊ตฌ ๊ด€๊ณ„๋ฅผ ๊ฐ€์ง„ ์‚ฌ๋žŒ A, B, C, D, E๊ฐ€ ์กด์žฌํ•˜๋Š”์ง€ ๊ตฌํ•ด๋ณด๋ ค๊ณ  ํ•œ๋‹ค.

  • A๋Š” B์™€ ์นœ๊ตฌ๋‹ค.
  • B๋Š” C์™€ ์นœ๊ตฌ๋‹ค.
  • C๋Š” D์™€ ์นœ๊ตฌ๋‹ค.
  • D๋Š” E์™€ ์นœ๊ตฌ๋‹ค.
  • ์ฒ˜์Œ์— ํ•ด๋‹น ์กฐ๊ฑด์„ ์‚ฌ์ดํด์ด ์กด์žฌํ•˜๋Š” ๊ทธ๋ž˜ํ”„๋ผ๊ณ  ์ดํ•ดํ–ˆ์œผ๋‚˜ ๊นŠ์ด๊ฐ€ 4๋ณด๋‹ค ๊นŠ์œผ๋ฉด 1์„ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋ฉด ๋œ๋‹ค๋Š” ๋œป์ด์—ˆ๋‹ค..!
  • ๊นŠ์ด๋ฅผ ์ƒ๊ฐํ•ด์ค˜์•ผํ•˜๋ฏ€๋กœ DFS๋กœ ํ’€์–ด์•ผ๊ฒ ๋‹ค! ๋ผ๊ณ  ์ƒ๊ฐํ–ˆ์œผ๋ฉฐ DFS, BFS์ฝ”๋“œ ๊ฐ™์€ ๊ฒฝ์šฐ ๋‚˜๋Š”.. ๋™๋นˆ๋‚˜์ƒ˜์˜ ์ด์ฝ”ํ…Œ ์ฝ”๋“œ๋ฅผ ์™ธ์› ๊ธฐ ๋•Œ๋ฌธ์—^^; ์ด๋ฅผ ํ™œ์šฉํ•ด์ฃผ์—ˆ๋‹ค.
  • ๊นŠ์ด๊ฐ€ 5์ผ ๊ฒฝ์šฐ True๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ค˜์•ผ ํ•˜๋ฏ€๋กœ dfs์ฝ”๋“œ์— depth์ธ์ž๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ์—ˆ๋‹ค.
  • 5๊ฐœ์˜ ๋…ธ๋“œ ํƒ์ƒ‰์„ ์„ฑ๊ณตํ•˜๋Š” dfs๊ฐ€ ํ•˜๋‚˜๋ผ๋„ ์žˆ๋Š”์ง€ ํƒ์ƒ‰ํ•ด์•ผ ํ•˜๋ฏ€๋กœ ๋…ธ๋“œ๋ฅผ ํ•˜๋‚˜ํ•˜๋‚˜ ๋Œ์•„๋ณด๋ฉด์„œ ๊ด€์ฐฐํ•ด์•ผํ•œ๋‹ค. ๋”ฐ๋ผ์„œ dfsํ•จ์ˆ˜ ๋งˆ์ง€๋ง‰์— visited[start] = False๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ์—ˆ๋‹ค.
# ABCDE
import sys
input = sys.stdin.readline

N, M = map(int, input().split())
graph = [[] for _ in range(N+1)]
visited = [0] * (N+1)
answer = False

for _ in range(M):
    a, b = map(int, input().split())
    graph[a].append(b)
    graph[b].append(a)

def dfs(graph, start, visited, depth):
    global answer
    visited[start] = True
    
    # ๊นŠ์ด๊ฐ€ 5๋ฉด True ๋ฐ˜ํ™˜
    if depth == 5:
        answer = True
        return
    
    for i in graph[start]:
        if not visited[i]:
            dfs(graph, i, visited, depth+1)
    visited[start] = False

for i in range(N):
    dfs(graph, i, visited, 1)
    if answer:
        break

if answer:
    print(1)
else:
    print(0)
profile
์ค‘์š”ํ•œ ๊ฒƒ์€ ๊บพ์ด์ง€ ์•Š๋Š” ๋งˆ์Œ

0๊ฐœ์˜ ๋Œ“๊ธ€