[Python] 백준 2667번: 단지번호붙이기

민지의 회고록·2023년 1월 31일

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

  • 사용언어 python

1. 문제

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.

2. 코드


import sys

sys.stdin = open("input.txt", "r")
from collections import deque


def bfs(startx, starty):
    if board[starty][startx] == '0' or (board[starty][startx] == '1' and visited[starty][startx]):
        return
    needVisited = deque([[startx, starty]])
    controlx = [1, -1, 0, 0]
    controly = [0, 0, 1, -1]
    visited[starty][startx] = True
    cnt = 1
    while needVisited:
        nowx, nowy = needVisited.popleft()
        for i in range(4):
            nextx, nexty = nowx + controlx[i], nowy + controly[i]
            if -1 < nextx < n and -1 < nexty < n:
                if not visited[nexty][nextx] and board[nexty][nextx] == '1':
                    visited[nexty][nextx] = True
                    needVisited.append([nextx, nexty])
                    cnt += 1
    ans.append(cnt)


def solution():
    global board, ans, n, visited
    n = int(input())
    board = []
    ans = []
    visited = [[False for _ in range(n)] for _ in range(n)]
    for i in range(n):
        board.append(list(input()))
    for i in range(n):
        for j in range(n):
            bfs(j, i)
    print(len(ans))
    for i in sorted(ans):
        print(i)

3. 풀이

1. 노드 탐색 메소드

def bfs(startx, starty):
    if board[starty][startx] == '0' or (board[starty][startx] == '1' and visited[starty][startx]):
        return
    needVisited = deque([[startx, starty]])
    	
    # 근접 노드 탐색
    controlx = [1, -1, 0, 0] # 좌우	
    controly = [0, 0, 1, -1] # 상하
    
    # 탐색 시작 노드 방문 처리
    visited[starty][startx] = True
    cnt = 1 # 단지 수 count
    
    
    while needVisited:
    	# 큐에서 노드를 꺼냄
        nowx, nowy = needVisited.popleft()
        
        # 빼낸 노드의 대한 인접 노드 탐색
        for i in range(4):
            nextx, nexty = nowx + controlx[i], nowy + controly[i] # 다음 노드
     		
            # 해당 그래프에 노드가 포함되어 있는지 확인
            if -1 < nextx < n and -1 < nexty < n:
            	# 해당 노드가 단지이고 방문 여부 확인
                if not visited[nexty][nextx] and board[nexty][nextx] == '1':
                    visited[nexty][nextx] = True
                    needVisited.append([nextx, nexty])
                    cnt += 1
    ans.append(cnt)

2. 메인 메소드

def solution():
    global board, ans, n, visited
    n = int(input())
    board = []
    ans = []
    
    # False 로 찬 2차원 리스트 생성
    visited = [[False for _ in range(n)] for _ in range(n)]
    
    # input 값으로 그래프 그리기
    for i in range(n):
        board.append(list(input()))
        
    # 노드 탐색
    for i in range(n):
        for j in range(n):
            bfs(j, i)
    print(len(ans))
    for i in sorted(ans):
        print(i)
profile
민지가 공부한 내용을 회고합니다~~

0개의 댓글