ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

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

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

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ์ฃผ์–ด์ง„ ์ง€๋„์—์„œ ์„ฌ์˜ ๊ฐœ์ˆ˜๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. 2667 ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ์™€ ์œ ์‚ฌํ•œ ๋ฌธ์ œ์ด์ง€๋งŒ ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ ์ถ”๊ฐ€๋œ ๋ฌธ์ œ์ด๋‹ค. ์ƒํ•˜์ขŒ์šฐ๋ฟ ์•„๋‹ˆ๋ผ, ๋Œ€๊ฐ์„ ์œผ๋กœ ์ธ์ ‘ํ•œ ๊ฒฝ์šฐ๋„ ๊ฐ™์€ ์„ฌ์œผ๋กœ ํŒ๋‹จํ•œ๋‹ค. ์ฆ‰, ์œ„์˜ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด ํ•˜๋‚˜์˜ ์ ์—์„œ ์ด 8๋ฐฉํ–ฅ์œผ๋กœ ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•˜๋ฉด ๋œ๋‹ค.

 

์ฝ”๋“œ

from sys import stdin
from collections import deque


def visitable(x, y):
    return 0 <= x < h and 0 <= y < w and graph[x][y]


def bfs(start):
    q = deque([start])
            # ์ƒ, ํ•˜, ์ขŒ, ์šฐ
    dirs = ((-1, 0), (1, 0), (0, 1), (0, -1),
            # ๋Œ€๊ฐ์„ 
            (-1, 1), (-1, -1), (1, -1), (1, 1))

    while q:
        cur_x, cur_y = q.popleft()
        for x, y in dirs:
            next_x, next_y = cur_x + x, cur_y + y
            if visitable(next_x, next_y):
                graph[next_x][next_y] = 0
                q.append([next_x, next_y])

    return 1

if __name__ == "__main__":
    while True:
        w, h = map(int, stdin.readline().split())

        if not w and not h:
            break

        graph = [list(map(int, stdin.readline().split())) for _ in range(h)]
        answer = 0
        print(graph)
        for x in range(h):
            for y in range(w):
                if graph[x][y]:
                    graph[x][y] = 0
                    answer += bfs([x, y])
        print(answer)

 ๋ณดํ†ต ๊ทธ๋ž˜ํ”„๋ฅผ N * M์œผ๋กœ ์ฃผ๋Š” ๋ฐ˜๋ฉด ์ด ๋ฌธ์ œ๋Š” W, H๋กœ ์ฃผ์–ด x, y์˜ ๋ฒ”์œ„๋ฅผ H, W๋กœ ํ•˜์—ฌ์•ผ ํ•œ๋‹ค๋Š” ์ฐจ์ด๋„ ์žˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€