본문 바로가기
알고리즘/Python

[백준] 파이썬 - 백준 2667번 : 단지번호붙이기

by 조이은 2023. 6. 20.

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

 

2667번: 단지번호붙이기

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여

www.acmicpc.net

백준 2667번 : 단지번호붙이기

 

 

# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(3000)
n = int(input())

res = []
graph = []
dx = [0,0,1,-1]
dy = [1,-1,0,0]

for i in range(n) :
    graph.append(list(map(int, input())))
        
def dfs(x,y) :
    global house
    
    if x<0 or x>=n or y<0 or y>=n :
        return False
    
    if graph[x][y] == 1 :
        graph[x][y] = 0
        house += 1
        
        for i in range(4) :
            nx = x+dx[i]
            ny = y+dy[i]
            
            dfs(nx, ny)
        return True
    return False

house = 0
count = 0
for i in range(n) :
    for j in range(n) :
        if dfs(i,j) == True:
            count+= 1
            res.append(house)
            house = 0
            
print(count)   
res.sort()
print(res)

 

dfs bfs 니가 이기나 내가 이기나 보자^^.. 완벽하게 풀때까지 다 풀어줄게