๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
  • What would life be If we had no courage to attemp anything?
Problem Solving/BAEKJOON

[baekjoon]python #2667 ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ

by DevIseo 2023. 1. 25.

[baekjoon]python #2667 ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ

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

 

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

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

www.acmicpc.net

import sys
input = sys.stdin.readline
from collections import deque

n = int(input())
arr = [list(map(int,input().strip())) for _ in range(n)]

#์ง‘์˜ ์ˆ˜
answer = []
#๋‹จ์ง€ ์ˆ˜
cnt=0


def bfs(y,x):
    queue = deque()
    queue.append((y,x))
    # ์ด๋ฏธ ๋‹ค๋…€๊ฐ„ ๊ณณ ์ฒดํฌ
    arr[y][x] = 0
	
    # ์ง‘์˜ ์ˆ˜ ์ฒดํฌ
    bfs_cnt = 0
    while queue:
        ny,nx = queue.popleft()

        directy = [-1,1,0,0]
        directx = [0,0,-1,1]

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

            if 0<=dy<n and 0<=dx<n:
                if arr[dy][dx]==1:
                	#๋‹ค๋…€๊ฐ„ ๊ณณ ์ฒดํฌ
                    arr[dy][dx] = 0
                    queue.append((dy,dx))
        bfs_cnt+=1
    answer.append(bfs_cnt)

for i in range(n):
    for j in range(n):
        if arr[i][j] == 1:
            bfs(i,j)
            cnt+=1

#์˜ค๋ฆ„์ฐจ์ˆœ
answer.sort()

#์ถœ๋ ฅ
print(cnt)
for a in answer:
    print(a)

๋Œ“๊ธ€