[Algorithm] ๐Ÿšฉ[๋ฐฑ์ค€] 1012 (Feat. BFS, ๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰)

myeonjiยท2022๋…„ 2์›” 4์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
30/89
post-custom-banner

BFS ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ดํ•ดํ•˜๊ธฐ ์ „์— ๋จผ์ €, ๊ทธ๋ž˜ํ”„ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ดํ•ดํ•ด์•ผ ํ•œ๋‹ค.

> ๊ทธ๋ž˜ํ”„(ํŠธ๋ฆฌ, tree) ํƒ์ƒ‰

ํ•˜๋‚˜์˜ ๋…ธ๋“œ์—์„œ ์‹œ์ž‘ํ•ด์„œ ๋‹ค๋ฅธ ๋…ธ๋“œ๋“ค์„ ๋ฐฉ๋ฌธํ•˜๋Š” ๊ฒƒ
๊ทธ๋ž˜ํ”„๋Š” ๋…ธ๋“œ์™€ ๊ฐ„์„ ์œผ๋กœ ํ‘œํ˜„๋œ๋‹ค.
๋‘ ๋…ธ๋“œ๊ฐ€ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋‹ค๋ฉด, ๋‘ ๋…ธ๋“œ๋Š” ์ธ์ ‘ํ•ด ์žˆ๋‹ค๋ผ๊ณ  ๋งํ•œ๋‹ค.

  • ๋ฃจํŠธ ๋…ธ๋“œ : ๋ถ€๋ชจ ๋…ธ๋“œ๊ฐ€ ์—†๋Š” ์ตœ์ƒ์œ„ ๋…ธ๋“œ
  • ๋‹จ๋ง ๋…ธ๋“œ : ์ž์‹ ๋…ธ๋“œ๊ฐ€ ์—†๋Š” ๋…ธ๋“œ
  • ํฌ๊ธฐ : ๋ชจ๋“  ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜
  • ๊นŠ์ด : ๋ฃจํŠธ ๋…ธ๋“œ๋กœ๋ถ€ํ„ฐ ๊ฑฐ๋ฆฌ
  • ๋†’์ด : ๊นŠ์ด์˜ ์ตœ๋Œ“๊ฐ’
  • ์ฐจ์ˆ˜ : ๋…ธ๋“œ๋ณ„ ๊ฐ„์„  ๊ฐœ์ˆ˜

> BFS

๊ทธ๋ž˜ํ”„์—์„œ ๊ฐ€๊นŒ์šด ๋…ธ๋“œ๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜
( <-> DFS, ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ : ๊ทธ๋ž˜ํ”„์—์„œ ๊ฐ€์žฅ ๋ฉ€๋ฆฌ ์žˆ๋Š”(๊นŠ์ˆ™ํ•œ) ๋…ธ๋“œ๋ฅผ ์šฐ์„ ์ ์œผ๋กœ ํƒ์ƒ‰ํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜ )

  • ๋‘ ๋…ธ๋“œ ์‚ฌ์ด์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ ํ˜น์€ ์ž„์˜์˜ ๊ฒฝ๋กœ๋ฅผ ์ฐพ์„ ๋•Œ ์‚ฌ์šฉ
  • ํ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์„ ์ž…์„ ์ถœ(FIFO) ์›์น™์œผ๋กœ ํƒ์ƒ‰

> BFS ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋™์ž‘ ๊ณผ์ •

  1. ํƒ์ƒ‰ ์‹œ์ž‘ ๋…ธ๋“œ๋ฅผ ํ์— ์‚ฝ์ž… ํ›„ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
  2. ํ์—์„œ ๋…ธ๋“œ๋ฅผ ๊บผ๋‚ด ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ธ์ ‘ ๋…ธ๋“œ๋ฅผ ํ์— ์‚ฝ์ž… ํ›„ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
  3. 2๋ฒˆ ๊ณผ์ •์„ ๋๊นŒ์ง€ ์ˆ˜ํ–‰

์ด ๋ฌธ์ œ๋Š” queue๋ฅผ ์ด์šฉํ•ด๋„ ๋˜๊ณ , deque๋ฅผ ์ด์šฉํ•ด๋„ ๋œ๋‹ค.
๋‚˜๋Š” ์–‘์ชฝ์—์„œ append, pop์„ ํ•  ์ˆ˜ ์žˆ๋„๋ก deque๋ฅผ ์ด์šฉํ•˜์˜€๋‹ค.

ํ’€์ด -> ๊ตฌ์—ญ๋งˆ๋‹ค ๋‚˜๋ˆ ์„œ ์ƒ๊ฐํ–ˆ๋‹ค. ํ•œ ๊ตฌ์—ญ๋งˆ๋‹ค ์ง€๋ ์ด 1๋งˆ๋ฆฌ๊ฐ€ ํ•„์š”ํ•œ ๊ฒƒ์ด๋‹ค. ๊ทธ๋ž˜ํ”„ ๊ฐ ์นธ์„ ๋Œ๋‹ค๊ฐ€ 1์ธ ์นธ์„ ๋ฐœ๊ฒฌํ•˜๋ฉด BFS๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค.
์ฆ‰, ํ•œ ๊ตฌ์—ญ์— BFS๊ฐ€ ํ•œ ๋ฒˆ ์ˆ˜ํ–‰๋˜๋Š” ๊ฒƒ์ด๋‹ค. BFS๊ฐ€ ์ˆ˜ํ–‰๋˜๊ณ  ๋‚˜๋ฉด ๊ทธ ๊ตฌ์—ญ์˜ 1์ด ๋ชจ๋‘ 0์œผ๋กœ ๋ฐ”๋€๋‹ค. ๋”ฐ๋ผ์„œ ์ง€๋ ์ด๋Š” BFS๊ฐ€ ์ˆ˜ํ–‰๋  ๋•Œ๋งˆ๋‹ค ์นด์šดํŠธ +1 ์ด ๋œ๋‹ค.

๊ผฌ๋ฆฌ์˜ ๊ผฌ๋ฆฌ๋ฅผ ๋ฌผ์–ด ํ’€์–ด๋‚˜๊ฐ€๋Š” ๊ฒƒ ๊ฐ™๋‹ค๋Š” ๋Š๋‚Œ์ด ๋“ค์—ˆ๋‹ค.

<ํ’€์ด>

from collections import deque

dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]

t = int(input())

def bfs(a, b):
    queue = deque()
    queue.append((a, b))
    graph[a][b] = 0

    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < m and graph[nx][ny] == 1:
                graph[nx][ny] = 0
                queue.append((nx, ny))


for i in range(t):
    cnt = 0
    m, n, k = map(int, input().split())
    graph = [[0]*m for _ in range(n)]

    for j in range(k):
        x, y = map(int, input().split())
        graph[y][x] = 1

    for a in range(n):
        for b in range(m):
            if graph[a][b] == 1:
                bfs(a, b)
                cnt += 1

    print(cnt)

<์ฐธ๊ณ >
๊ทธ๋ž˜ํ”„ ์ž๋ฃŒ๊ตฌ์กฐ

profile
DBA, ๊ฒฝ์ œ ๊ทธ๋ฆฌ๊ณ  ๊ณ ๋ƒฅ์ด
post-custom-banner

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