ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค [lv3] floodfill ํŒŒ์ด์ฌ

2021. 9. 1. 21:55ใ†๐Ÿ”ฑ Algorithm

 

๐Ÿ•น  ์ฝ”๋“œ 

from collections import deque


def solution(n, m, images):
    directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    answer = 0

    for r in range(n):
        for c in range(m):
            if images[r][c] == -1:
                continue  # continue ์™€ pass
            color = images[r][c]
            queue = deque([(r, c)])
            while queue:
                y, x = queue.popleft()
                for ny, nx in directions:
                    py = ny + y
                    px = nx + x
                    if (0 <= py < n) and (0 <= px < m) and (images[py][px] == color):
                        images[py][px] = -1
                        queue.append((py, px))
            answer += 1
    return answer

 

 

๐ŸŽ†  ๊ณ ์ฐฐ๊ณผ ์‹œํ–‰์ฐฉ์˜ค

images[py][px] = -1  ๋กœ ๊ธฐ์ค€ ๋…ธ๋“œ๊ฐ€ ์•„๋‹Œ ์ฃผ๋ณ€๋…ธ๋“œ๋ฅผ -1 ๋กœ ๋ฐ”๊พธ๋Š”๋ฐ, color ๋Š” ์ฃผ๋ณ€ ๋…ธ๋“œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ •ํ•ด์ง„ ๊ฒƒ์ด ์•„๋‹Œ ์ตœ์ดˆ ๊ธฐ์ค€ ๋…ธ๋“œ๋กœ ๋ฏธ๋ฆฌ ์ •ํ•ด์ ธ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.  ๊ทธ๋ž˜์„œ ์ฃผ๋ณ€ ๋…ธ๋“œ๋ฅผ -1 ๋กœ ๋ฐ”๊พธ๋Š” ๊ฒƒ์€ ๋ฌธ์ œ๊ฐ€ ๋˜์ง€ ์•Š๋Š”๋‹ค.

answer += 1 ์„ ์„ ์–ธํ•˜๋Š” ์œ„์น˜๋ฅผ ์ž˜๋ชป์žก์•˜๋Š”๋ฐ, if ๋ฌธ ๋‚ด๋ถ€์—์„œ ํ•ด๋‹น ๋กœ์ง์ด ์ˆ˜ํ–‰๋ผ์•ผ ํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค.
ํ•˜์ง€๋งŒ ๋ฌธ์ œ์—์„œ ์›ํ•˜๋Š” ๋‹ต์€ ๊ฐ™์€ ์นผ๋ผ๊ฐ€ ์žˆ์„ ๋•Œ๋งˆ๋‹ค answer ๋ฅผ +1 ํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ, ํ•˜๋‚˜์˜ ๊ทธ๋ฃน์ด ์ƒ๊ธธ ๋•Œ๋งˆ๋‹ค + 1์„ ํ•˜๋Š” ๊ฒƒ์ด๋ผ ํ•œ๋‹ค. ๋˜ ์ฃผ๋ณ€์— ๊ฐ™์€ color๊ฐ€ ํ•˜๋‚˜๋„ ์—†๋”๋ผ๋„ queue ๋ฅผ ๋‹ค ์ˆœํšŒํ•˜๊ณ  ๋‚˜๋ฉด ์ž์‹  ๋…ธ๋“œ์˜ ์ƒ‰๊น”์€ + 1 ํ•ด์•ผํ•œ๋‹ค.

 

 

 

๐ŸŽ‡  pass ์™€ continue

continue ๋Š” ๋ฃจํ”„ ๋‚ด์—์„œ ์ฒ˜๋ฆฌํ•  ๋กœ์ง์ด ์•„๋ž˜์— ๋” ๋‚จ์•„์žˆ์ง€๋งŒ, ์ด๋ฅผ ๊ฑด๋„ˆ๋›ฐ๊ณ  ๋‹ค์Œ ๋ฃจํ”„๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค.

์ฆ‰, ๊ฐ™์€ scope ์—์„œ  continue ๊ฐ€ ๋จผ์ € ๋‚˜์˜จ ํ›„์—๋„ ์ฒ˜๋ฆฌํ•ด์•ผํ•  ๋กœ์ง์ด ์žˆ๋‹ค๋ฉด, continue ์ดํ›„ ๋กœ์ง์€ ์ž์—ฐ์Šค๋ ˆ ์Šคํ‚ต๋œ๋‹ค.

 

pass๋Š” ์‹คํ–‰ํ•  ์ฝ”๋“œ๊ฐ€ ์—†๋Š” ๊ฒƒ์œผ๋กœ ๋‹ค์Œ ํ–‰๋™์„ ๊ณ„์† ์ง„ํ–‰๋œ๋‹ค.

์ด๋Ÿฐ ๊ด€์ ์—์„œ ๋ณด๋ฉด pass ๋Š” ๋ณ„๋‹ค๋ฅธ ์˜ํ–ฅ์„ ๋ผ์ง€์น˜ ์•Š๊ธฐ์— ์šฉ๋„๋ฅผ ์ž˜ ๋ชจ๋ฅผ ์ˆ˜ ์žˆ์ง€๋งŒ, ์˜ˆ์™ธ๋‚˜ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ, pass ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์—๋Ÿฌ๊ฐ€ ์ƒ๊ธฐ๋”๋ผ๋„ ๊ณ„์† ์ฝ”๋“œ๋ฅผ ์ง„ํ–‰์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค.

์ฃผ๋กœ try ~ except ๋ฌธ์˜ except ๋‚ด์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งŽ๋‹ค.