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

[Python Algorithm] ์„ฌ์˜ ๊ฐœ์ˆ˜ BOJ #4963

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

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

 

4963๋ฒˆ: ์„ฌ์˜ ๊ฐœ์ˆ˜

์ž…๋ ฅ์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ์ฒซ์งธ ์ค„์—๋Š” ์ง€๋„์˜ ๋„ˆ๋น„ w์™€ ๋†’์ด h๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. w์™€ h๋Š” 50๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์–‘์˜ ์ •์ˆ˜์ด๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ h๊ฐœ ์ค„์—๋Š” ์ง€๋„

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import sys
sys.setrecursionlimit(10000)

while True:
    w, h = map(int, sys.stdin.readline().split())
    if w == 0 and h == 0:
        break

    space = [list(map(int, sys.stdin.readline().split())) for _ in range(h)]
    dx = [0, 0, -1, 1, -1, 1, -1, 1]
    dy = [-1, 1, 0, 0, -1, 1, 1, -1]
    count = 0

    def dfs(x, y):
        for i in range(8):
            nx = x + dx[i]
            ny = y + dy[i]

            if nx < 0 or ny < 0 or nx >= h or ny >= w or space[nx][ny] == 0: continue

            space[nx][ny] = 0
            dfs(nx, ny)

    for i in range(h):
        for j in range(w):
            if space[i][j] == 1:
                count += 1
                space[i][j] = 0
                dfs(i, j)

    print(count)

๐Ÿ‘‰ DFS ๋ฌธ์ œ๋กœ, ์ด์–ด์ง„ ์„ฌ๋“ค์„ ํ•œ ๋ฒˆ์— ์ฒดํฌํ•ด์ฃผ๋Š” ๊ฒƒ์ด ํฌ์ธํŠธ !

  • ์ฃผ์–ด์ง„ ์ง€๋„ space ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœ์ฐจ์ ์œผ๋กœ ๋Œ๋ฉด์„œ 1์ด ๋“ฑ์žฅํ•˜๋ฉด
    ๊ทธ ์ž๋ฆฌ๋ฅผ 0์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ๊ณ , count๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ ํ›„ dfs ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ–ˆ๋‹ค.
  • dfs ํ•จ์ˆ˜์—์„œ๋Š” ์ƒํ•˜์ขŒ์šฐ, ๊ทธ๋ฆฌ๊ณ  ๋Œ€๊ฐ์„ ๊นŒ์ง€ ์ด 8๊ณณ์„ ํƒ์ƒ‰ํ–ˆ๊ณ 
    1์„ ๋ฐœ๊ฒฌํ•˜๋ฉด ๊ทธ ์ž๋ฆฌ๋ฅผ 0์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ๊ณ , ๋˜ ๊ทธ ์ฃผ๋ณ€์„ ํƒ์ƒ‰ํ•˜๊ฒŒ ํ–ˆ๋‹ค.
    ์ด์–ด์ง„ ๋ชจ๋“  ์„ฌ์ด 0์œผ๋กœ ๋ฐ”๋€Œ๋ฉด dfs ํ•จ์ˆ˜๋Š” ์ข…๋ฃŒ๋œ๋‹ค.
  • ์ด๋ ‡๊ฒŒ ์ด์–ด์ง„ ์„ฌ๋“ค์„ ๋ชจ๋‘ 0์œผ๋กœ ๋ฐ”๊พผ ๋’ค, ๋‹ค์‹œ ๋˜ ๋‹ค๋ฅธ ์„ฌ์ด ์žˆ๋Š”์ง€ ์ฐพ๋Š”๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ๊ต‰์žฅํžˆ ์‰ฝ๊ณ , ๊ต‰์žฅํžˆ ์ „ํ˜•์ ์ธ,,! DFS ๋ฌธ์ œ์˜€๋‹ค.
  • sys.setrecursionlimit์„ ํ•ด์ฃผ์ง€ ์•Š์œผ๋ฉด ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ๊ฐ€ ๋‚˜๋”๋ผ. ๊ผญ ํ•ด์ฃผ์„ธ์šฉ

๋Œ“๊ธ€