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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

2667๋ฒˆ: ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ

<๊ทธ๋ฆผ 1>๊ณผ ๊ฐ™์ด ์ •์‚ฌ๊ฐํ˜• ๋ชจ์–‘์˜ ์ง€๋„๊ฐ€ ์žˆ๋‹ค. 1์€ ์ง‘์ด ์žˆ๋Š” ๊ณณ์„, 0์€ ์ง‘์ด ์—†๋Š” ๊ณณ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค. ์ฒ ์ˆ˜๋Š” ์ด ์ง€๋„๋ฅผ ๊ฐ€์ง€๊ณ  ์—ฐ๊ฒฐ๋œ ์ง‘๋“ค์˜ ๋ชจ์ž„์ธ ๋‹จ์ง€๋ฅผ ์ •์˜ํ•˜๊ณ , ๋‹จ์ง€์— ๋ฒˆํ˜ธ๋ฅผ ๋ถ™์ด๋ ค ํ•œ๋‹ค. ๏ฟฝ

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ์ง€๋„์—์„œ ์˜์—ญ์„ ํƒ์ƒ‰ํ•˜์—ฌ ๋‹จ์ง€๊ฐ€ ๋ช‡ ๊ฐœ์ธ์ง€ ํ™•์ธํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ๋‹จ์ง€๋ฅผ ํ™•์ธ ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” BFS๋ฅผ ํ†ตํ•ด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์กฐ๊ฑด์„ ํ™•์ธํ•˜๋ฉฐ ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•˜๋ฉด ๋œ๋‹ค.

 

  • ๋ชจ๋“  ์‹œ์ž‘์ ์„ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด 2์ค‘ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ N * N ๋งŒํผ์˜ ์‹œ์ž‘์ ์„ ํƒ์ƒ‰ํ•œ๋‹ค.
  • ์‹œ์ž‘์ ์ด ๋‹จ์ง€(1์ธ ๊ฒฝ์šฐ)๋ผ๋ฉด ์‹œ์ž‘์ ์„ ๊ธฐ์ค€์œผ๋กœ ์ƒ, ํ•˜, ์ขŒ, ์šฐ๋กœ ํƒ์ƒ‰ํ•˜์—ฌ ์—ฐ๊ฒฐ๋œ ์ง‘์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.
    • ์ง€๋„ ๋‚ด์— ์œ„์น˜ํ•˜๋Š”์ง€ ํ™•์ธ ํ•˜๊ธฐ ์œ„ํ•ด 0 <= x < N && 0 <= y < N๊ณผ ๊ฐ™์€ ์กฐ๊ฑด์ด ํ•„์š”ํ•˜๋‹ค.
    • ๋ฐฉ๋ฌธ ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ graph[x][y]๋Š” 1์ด์—ฌ์•ผ ํ•œ๋‹ค.
  • ํ•˜๋‚˜์˜ ์ ์„ ์‹œ์ž‘์œผ๋กœ ์ƒ, ํ•˜, ์ขŒ, ์šฐ๋กœ ํƒ์ƒ‰์„ ๋„“ํžˆ๋ฉด์„œ ๋” ์ด์ƒ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ง‘์ด ์—†๋‹ค๋ฉด ํ•˜๋‚˜์˜ ๋‹จ์ง€์— ๋Œ€ํ•œ ํƒ์ƒ‰์„ ์™„๋ฃŒํ•œ ๊ฒƒ์ด๋‹ค.

 

์ฝ”๋“œ

from sys import stdin
from collections import deque


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


def bfs(start):
    q = deque([start])
    dirs = ((-1, 0), (1, 0), (0, 1), (0, -1))
    cnt = 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])
                cnt += 1
    return cnt


if __name__ == "__main__":
    n = int(stdin.readline())
    graph = [list(map(int, stdin.readline().strip())) for _ in range(n)]
    answer = []

    for x in range(n):
        for y in range(n):
            if graph[x][y]:
                graph[x][y] = 0
                answer.append(bfs([x, y]))

    print(len(answer))
    print('\n'.join(map(str, sorted(answer))))

 ํƒ์ƒ‰ํ•œ ์ง‘์„ 0์œผ๋กœ ํ‘œ์‹œํ•˜๋ฉด ์žฌํƒ์ƒ‰์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๋ฏ€๋กœ, ๋ณ„๋„์˜ visited ๋ฆฌ์ŠคํŠธ๋ฅผ ํ†ตํ•ด ์ฒดํฌํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.

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