Algorithm/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€(BOJ) / Python] 1260๋ฒˆ: DFS์™€ BFS

meeeeejin 2021. 3. 15. 22:25

๋ฌธ์ œ ๋งํฌ: www.acmicpc.net/problem/1260

 

1260๋ฒˆ: DFS์™€ BFS

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 1,000), ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 10,000), ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์ ์˜ ๋ฒˆํ˜ธ V๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ„์„ ์ด ์—ฐ๊ฒฐํ•˜๋Š” ๋‘ ์ •์ ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์–ด๋–ค ๋‘ ์ •์  ์‚ฌ

www.acmicpc.net

 

 

๋ฌธ์ œ ์„ค๋ช…

๋‹จ์ˆœํžˆ DFS์™€ BFS๋ฅผ ์ˆ˜ํ–‰ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ €๋Š” (N + 1) X (N + 1) ํฌ๊ธฐ์˜ matrix๋ฅผ ์ด์šฉํ•ด ์ •์  ๊ฐ„์˜ ๊ฐ„์„ ์„ ํ‘œ์‹œํ–ˆ์Šต๋‹ˆ๋‹ค.

๋˜ํ•œ dfs๋ฅผ ํ•  ๋• ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋ฅผ 1๋กœ ํ‘œํ˜„ํ•˜๊ณ  bfs๋ฅผ ํ•  ๋• 0์œผ๋กœ ํ‘œํ˜„ํ•ด์„œ visited๋ฅผ ๋”ฐ๋กœ ์ดˆ๊ธฐํ™”ํ•  ํ•„์š” ์—†์ด ๋ฐ”๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ํ–ˆ์Šต๋‹ˆ๋‹ค. 

 

 

 

์†Œ์Šค์ฝ”๋“œ

def dfs(v):
    # ๋ฐฉ๋ฌธ ๋…ธ๋“œ 1๋กœ ํ‘œํ˜„
    visited[v] = 1
    print(v, end = ' ')
    for i in range(1, n + 1):
        # ์ธ์ ‘ ๋…ธ๋“œ ์ค‘ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ ํƒ์ƒ‰
        if visited[i] == 0 and matrix[v][i] == 1:
            dfs(i)

def bfs(start):
    queue = [start]
    # ๋ฐฉ๋ฌธ ๋…ธ๋“œ 0์œผ๋กœ ํ‘œํ˜„
    visited[start] = 0

    while queue:
        v = queue.pop(0)
        print(v, end = ' ')
        for i in range(1, n + 1):
            # ์ธ์ ‘ ๋…ธ๋“œ ์ค‘ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ ๋ฐฉ๋ฌธ
            if visited[i] == 1 and matrix[v][i] == 1:
                queue.append(i)
                visited[i] = 0

n, m, v = map(int, input().split())
visited = [0] * (n + 1)
# matrix์— ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ ํ‘œ์‹œ
matrix = [[0] * (n + 1) for _ in range(n + 1)]
for _ in range(m):
    i, j = map(int, input().split())
    matrix[i][j] = 1
    matrix[j][i] = 1

dfs(v)
print()
bfs(v)

 

728x90