๐Ÿ˜ฅ ๋ฐฑ์ค€ 1260 : DFS์™€ BFS

3Juhwanยท2021๋…„ 2์›” 20์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
5/23

1260: DFS์™€ BFS

DFS/BFS ๊ฐœ๋…์„ ๊ณต๋ถ€ํ•˜๊ณ  ๋ฌธ์ œ ํ’€๊ธฐ ์‹œ์ž‘ํ–ˆ๋‹ค~!


๐Ÿ“Œ Try 1

import sys

def dfs(graph, visit, start_node, N):
    print(start_node, end=' ')
    
    stack = []
    for i in range(1, N + 1):
        if graph[start_node][i]:
            graph[start_node][i] = 0
            graph[i][start_node] = 0
            
            stack.append(i)
    
    while stack:
        node = stack.pop(0)
        
        if node not in visit:
            visit.append(node)
            dfs(graph, visit, node, N)

def bfs(start_node):
    queue = [start_node]
    visit = []
    
    while queue:
        start_node = queue.pop(0)
        visit.append(start_node)
        
        print(start_node, end=' ')
    
        # append step
        for i in range(1, N + 1):
            if i not in visit and i not in queue:
                graph[start_node][i] = 0
                graph[i][start_node] = 0
                queue.append(i)
        
        print('queue =', queue, 'visit =', visit)
    

N, M, V = map(int, sys.stdin.readline().rstrip().split())

# Construct Graph
graph = [[0] * (N + 1) for i in range(N + 1)]
visit = []
for i in range(M):
    x, y = map(int, sys.stdin.readline().rstrip().split())
    graph[x][y] = 1
    graph[y][x] = 1

dfs(graph, visit, V, N)

์ด ๋ฌธ์ œ์— ๊ฝค ๋งŽ์€ ์‹œ๊ฐ„์„ ์†Œ๋ชจํ–ˆ๋Š”๋ฐ๋„ ํ’€์ง€ ๋ชปํ–ˆ๋‹ค.
์ด์ „์— ์ •๋ฆฌํ•œ DFS/BFS ๊ธ€์˜ ํƒ์ƒ‰ ๋ฐ์ดํ„ฐ์™€ ํ˜•์‹์ด ๋‹ฌ๋ผ ์–ด๋–ป๊ฒŒ ์ ‘๊ทผํ•ด์•ผ ํ•˜๋Š”์ง€ ๋ชจ๋ฅด๊ฒ ๋‹ค.
์•„์ง DFS/BFS ๊ฐœ๋…์ด ๋ถ€์กฑํ•ด์„œ ์‘์šฉ์ด ์•ˆ๋˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค. ๐Ÿ˜ฅ


๐ŸŽฏ Solution

import sys

def dfs(start_node):
    print(start_node, end=' ')
    visit[start_node] = 1
    
    for i in range(1, N + 1):
        if graph[start_node][i] and visit[i] == 0:
            dfs(i)

def bfs(start_node):
    queue = [start_node]
    visit[start_node] = 0
    
    while queue:
        start_node = queue.pop(0)
        print(start_node, end=' ')
        
        for i in range(1, N + 1):
            if graph[start_node][i] and visit[i] == 1:
                queue.append(i)
                visit[i] = 0
    
# input
N, M, V = map(int, sys.stdin.readline().rstrip().split())

# Construct Graph
graph = [[0] * (N + 1) for i in range(N + 1)]
visit = [0 for i in range(N + 1)]

for i in range(M):
    x, y = map(int, sys.stdin.readline().rstrip().split())
    graph[x][y] = 1
    graph[y][x] = 1

# output
dfs(V)
print()
bfs(V)

์ฐธ๊ณ  ๋ธ”๋กœ๊ทธ ์ฝ”๋“œ๋ฅผ ์ฐธ๊ณ ํ•ด์„œ, ๊ฑฐ์˜ ์œ ์‚ฌํ•˜๋‹ค.
์•„์ง์€ ์–ด๋ ต๋‹ค,,,


๐ŸŽ Reference

profile
Codeforces์™€ USACO ํ’€์ด๋ฅผ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค. ์ด์ „ ๊ธ€๋„ ๊ณ„์† ์—…๋ฐ์ดํŠธ ๋ฉ๋‹ˆ๋‹ค.

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