๐Ÿ’ป Coding/[Algorithm]Python

BOJ | 2667_๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ - PYTHON

๐Ÿฉท ๋ฏผ์˜ 2024. 3. 20. 16:29

BOJ | 2667_๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ - PYTHON

 

๋ฌธ์ œ

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

 

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

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

www.acmicpc.net

 

 

์•Œ๊ณ ๋ฆฌ์ฆ˜

์ „ ๋ฐ์ดํ„ฐ๋ฅผ ๋Œ๋ฉด์„œ ์ง‘์ด ์žˆ์œผ๋ฉด์„œ, ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๊ณณ์„ ์ฐพ์•„์•ผํ–ˆ๊ธฐ์— DFS๋ฅผ ์‰ฝ๊ฒŒ ๋– ์˜ฌ๋ฆด ์ˆ˜ ์žˆ์—ˆ๋‹ค

 

๋‚ด ํ’€์ด

import sys
input = sys.stdin.readline

## 3. DFS
def DFS(x,y):
    global result
    stack = [(x,y)]
    # ๋ฐฉ๋ฌธํ•œ ๊ณณ์„ result(๋ช‡๋‹จ์ง€์ธ์ง€) ๊ฐ’์œผ๋กœ ๋ณ€ํ™˜
    visited[x][y] = result
    cnt = 1 # ๋‹จ์ง€ ๋ณ„ ์ง‘์ด ๋ช‡ ๊ฐœ ์žˆ๋Š”์ง€
    while stack:
        sx, sy = stack.pop()
        dx = [-1, 1, 0, 0] # ์ƒํ•˜์ขŒ์šฐ
        dy = [0, 0, -1, 1]
        for dir in range(4):
            nx = sx + dx[dir]
            ny = sy + dy[dir]
            if 0 <= nx < N and 0 <= ny < N:
                if data[nx][ny] == 1 and not visited[nx][ny]:
                    visited[nx][ny] = result
                    cnt += 1
                    stack.append((nx, ny))
    result += 1
    return cnt

## 1. ์ž…๋ ฅ ๋ฐ›๊ธฐ
N = int(input())
data = [list(map(int, input().rstrip())) for _ in range(N)]

visited = [[0]*N for _ in range(N)]
result = 1 # ๋‹จ์ง€ ์ˆ˜
result_list = [] # ๋‹จ์ง€ ์ˆ˜๋ฅผ ๋‹ด์€ ๋ฆฌ์ŠคํŠธ(๋‚˜์ค‘์— sortํ•ด์„œ ๋‹จ์ง€ ๋‚ด ์ง‘์˜ ์ˆ˜ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ)

## 2. ๋ฐฐ์—ด ๋Œ๋ฉด์„œ ์ง‘์ด ์žˆ๊ณ  ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜์„ ๊ฒฝ์šฐ์— DFS
for i in range(N):
    for j in range(N):
        if data[i][j] == 1 and not visited[i][j]:
            result_list.append(DFS(i,j))

## 4. ์ถœ๋ ฅ
result_list.sort()
print(len(result_list))

for i in result_list:
    print(i)