Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

세상의 모든 알고리즘

[백준 2667 python] 단지번호 붙이기 본문

python

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

952hi 2021. 11. 4. 18:00

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

 

2667번: 단지번호붙이기

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

www.acmicpc.net

 

전형적인 탐색문제로 DFS와 BFS 중 BFS로 문제를 풀어 보았습니다.

 

'''
7
0110100
0110101
1110101
0000111
0100000
0111110
0111000
'''
import sys
from collections import deque

input = sys.stdin.readline
numbering = []
result = []
n = int(input())

for _ in range(n):
    numbering.append(list(map(int,input().rstrip())))



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

def bfs(x,y):
    q = deque()
    q.append((x,y))
    numbering[x][y] = 2
    score = 1

    while q:
        a,b = q.popleft()
        for i in range(4):
            nx = a+dx[i]
            ny = b+dy[i]
            if nx >= 0 and nx < n and ny>= 0 and ny < n:
                if numbering[nx][ny] ==1:
                    numbering[nx][ny] = 2
                    q.append((nx,ny))
                    score += 1
    return score

for i in range(n):
    for j in range(n):
        if numbering[i][j] == 1:
            result.append(bfs(i,j))
result.sort()
print(len(result))
for i in result:
    print(i)

 

알게된 점

탐색문제를 풀때는 조건과 범위 설정이 중요하다는 점입니다. 범위에 = 하나를 빠트려 문제가 산으로 가서 오랜시간동안 코드를 쳐다보며 찾게되었습니다 ㅜㅜ..