๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] ์œ ๊ธฐ๋† ๋ฐฐ์ถ” BOJ #1012

by seolhee2750 2022. 1. 27.
๋ฌธ์ œ

https://www.acmicpc.net/problem/1012

 

1012๋ฒˆ: ์œ ๊ธฐ๋† ๋ฐฐ์ถ”

์ฐจ์„ธ๋Œ€ ์˜๋†์ธ ํ•œ๋‚˜๋Š” ๊ฐ•์›๋„ ๊ณ ๋žญ์ง€์—์„œ ์œ ๊ธฐ๋† ๋ฐฐ์ถ”๋ฅผ ์žฌ๋ฐฐํ•˜๊ธฐ๋กœ ํ•˜์˜€๋‹ค. ๋†์•ฝ์„ ์“ฐ์ง€ ์•Š๊ณ  ๋ฐฐ์ถ”๋ฅผ ์žฌ๋ฐฐํ•˜๋ ค๋ฉด ๋ฐฐ์ถ”๋ฅผ ํ•ด์ถฉ์œผ๋กœ๋ถ€ํ„ฐ ๋ณดํ˜ธํ•˜๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ํ•œ๋‚˜๋Š” ํ•ด์ถฉ ๋ฐฉ์ง€์— 

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
t = int(input())
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
queue = []

for _ in range(t):
    m, n, k = map(int, input().split())  # ๊ฐ€๋กœ๊ธธ์ด, ์„ธ๋กœ๊ธธ์ด, ๋ฐฐ์ถ” ๊ฐœ์ˆ˜
    space = [[0] * m for _ in range(n)]  # ๋ฐฐ์ถ”๋ฐญ
    count = 0

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

    def bfs():
        index = 0

        while len(queue) > index:
            x = queue[index][0]
            y = queue[index][1]
            index += 1

            for i in range(4):
                nx = x + dx[i]
                ny = y + dy[i]

                if nx < 0 or ny < 0 or nx >= n or ny >= m or space[nx][ny] == 0: continue

                space[nx][ny] = 0
                queue.append((nx, ny))

    for i in range(n):
        for j in range(m):
            if space[i][j] == 1:
                queue.append((i, j))
                space[i][j] = 0
                count += 1
                bfs()
                queue = []

    print(count)

๐Ÿ‘‰ bfs/dfs ๋ฌธ์ œ์ธ๋ฐ, dfs๋กœ ํ’€๋ฉด ๋” ์‰ฌ์šธ ๊ฒƒ ๊ฐ™์ง€๋งŒ ๋‚ด๊ฐ€ bfs์— ๋” ์•ฝํ•œ ๊ฒƒ ๊ฐ™์•„์„œ bfs๋กœ ํ’€์–ด๋ดค๋‹ค.

  • 2์ค‘ for๋ฌธ์œผ๋กœ ๋•…์„ ํ•œ ์นธ์”ฉ ํƒ์ƒ‰ํ•˜๋ฉด์„œ 1์ด ๋‚˜์˜ค๋ฉด bfs ํ•จ์ˆ˜๋ฅผ ๋Œ๋ ค์ฃผ์—ˆ๋‹ค.
  • bfs ํ•จ์ˆ˜์—์„œ๋Š” dx, dy ๋ฆฌ์ŠคํŠธ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ์ƒํ•˜์ขŒ์šฐ๋ฅผ ํƒ์ƒ‰ํ•ด์ฃผ์—ˆ๋‹ค.
    1์„ ๋งŒ๋‚œ๋‹ค๋ฉด queue์— ํ•ด๋‹น ์ž๋ฆฌ๋ฅผ ์ถ”๊ฐ€ํ•ด์„œ ํƒ์ƒ‰์„ ๊ณ„์†ํ•˜๋„๋ก ํ•ด์ฃผ์—ˆ๊ณ ,
    1์ด ์žˆ๋˜ ์ž๋ฆฌ๋Š” 0์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ์–ด ๋‹ค์‹œ ๊ฐ™์€ ํƒ์ƒ‰์„ ํ•˜์ง€ ์•Š๋„๋ก ํ–ˆ๋‹ค.

โœ”๏ธ ์ด ๋ฌธ์ œ์—์„œ ์ž˜ ์ฒดํฌํ•ด์ค˜์•ผ ํ•  ์ ์€,

๋‹ค๋ฅธ dfs, bfs ๋ฌธ์ œ์™€๋Š” ๋‹ค๋ฅด๊ฒŒ ๋ฐฐ์ถ”๊ฐ€ ์žˆ๋Š” ์ž๋ฆฌ๋ฅผ m, n์œผ๋กœ ํ‘œ์‹œํ•ด์ฃผ์—ˆ๊ธฐ ๋•Œ๋ฌธ์—
๋ฆฌ์ŠคํŠธ์—์„œ ํ•ด๋‹น ์ž๋ฆฌ๋ฅผ ์ฒดํฌํ•ด์ค„ ๋•Œ x, y๊ฐ€ ์•„๋‹ˆ๋ผ y, x๋กœ ๋ฐ”๊ฟ”์„œ ๋ฐฐ์ถ”์˜ ์ž๋ฆฌ๋ฅผ ๋„ฃ์–ด์ค˜์•ผ ํ•œ๋‹ค.

 

(์ด์ „์— swift๋ฅผ ์ด์šฉํ•ด์„œ dfs๋กœ ํ’€์—ˆ๋˜ ๊ฒŒ์‹œ๊ธ€ -> https://seolhee2750.tistory.com/129)

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์‰ฌ์šด ๋ฌธ์ œ๋ผ ๊ธˆ๋ฐฉ ํ’€์—ˆ๋Š”๋ฐ, ์ด์ƒํ•˜๊ฒŒ ์ž๊พธ ์˜ค๋ฅ˜๊ฐ€ ๋‚˜์„œ ๋ณด๋‹ˆ๊นŒ
    ํŒŒ์ด์ฌ์€ ๋…ผ๋ฆฌ ์—ฐ์‚ฐ์ž๋ฅผ || ๋ง๊ณ  or ๋ผ๊ณ  ์จ์•ผ๋˜๋”๋ผ,,!
    ํŒŒ์ด์ฌ์„ ์˜ค๋žœ๋งŒ์— ์“ฐ๋‹ˆ๊นŒ ๋˜ ํ—ท๊ฐˆ๋ฆฐ๋‹ค.ใ…Ž ํ™”์ดํŒ…,,

๋Œ“๊ธ€