백준 2667 - 파이썬

손찬호·2024년 4월 4일
0

알고리즘

목록 보기
9/91

풀이 아이디어

그래프를 재귀로 탐색하여
'1'과 '0'으로 집과 타일을 구분하고
'1'인 타일을 상하좌우로 탐색하고 '1'이면 재귀로 탐색하고
탐색한 집은 '0'으로 바꾼다.

풀이 코드

import sys
input = sys.stdin.readline

# 입력받기
n = int(input())
graph = []
for _ in range(n):
    graph.append(list(input().strip()))

# 단지수, 집수
houses = []

def dfs(start):
    global house
    x,y = start
    # 범위 밖을 벗어나면 종료
    if x < 0 or x >= n or y < 0 or y >= n:
        return
    # 집이 없으면 종료
    if graph[x][y] == '0':
        return
    # 방문한 집 0으로 바꿈
    graph[x][y] = '0'
    house += 1
    # 북남동서 방향 탐색
    dfs((x+1,y))
    dfs((x-1,y))
    dfs((x,y+1))
    dfs((x,y-1))

# 총 단지수
for i in range(n):
    for j in range(n):
        if graph[i][j] == '1':
            house = 0
            dfs((i,j))
            houses.append(house)
print(len(houses))

# 단지 내 집 수
houses.sort()
for house in houses:
    print(house)
profile
매일 1%씩 성장하려는 주니어 개발자입니다.

0개의 댓글

관련 채용 정보