728x90
반응형
https://www.acmicpc.net/problem/2667
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여
www.acmicpc.net
정답 code
-bfs이용
#단지번호붙이기
#bfs
from collections import deque
dx = [-1,1,0,0]
dy = [0,0,-1,1]
def bfs(a,b):
n = len(apt)
queue = deque()
queue.append((a,b))
apt[a][b] = 0
count = 1
while queue:
x,y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or nx >= n or ny < 0 or ny >= n :
continue
if apt[nx][ny] == 1:
queue.append((nx,ny))
apt[nx][ny] = 0
count += 1
return count
n = int(input())
apt = []
for i in range(n):
apt.append(list(map(int,input())))
cnt = []
for i in range(n):
for j in range(n):
if apt[i][j] == 1:
cnt.append(bfs(i,j))
cnt.sort()
print(len(cnt))
for i in range(len(cnt)):
print(cnt[i])
solution
이 문제는 다른 너비 우선탐색이나 깊이우선 탐색을 이용해 풀면되는데,
출력조건인 총 단지수와 단지내 집의 수를 오름차순 출력해야 한다.
이를 위해 cnt 리스트를 만들고 단지내 집의수를 넣은뒤
리스트의 길이를 단지수, 리스트 인덱스 하나하나를 출력해 집의 수를 출력하면 된다.
728x90
반응형
'알고리즘 > 백준[baekjoon]' 카테고리의 다른 글
[baekjoon] 백준 5525번 : IOIO (by python 파이썬) (0) | 2022.06.24 |
---|---|
[baekjoon] 백준 5430번 : AC (by python 파이썬) deque, join (0) | 2022.06.20 |
[baekjoon] 백준 11726번 : 2*n 타일링 (by python) 다이나믹프로그래밍 (0) | 2022.06.15 |
[baekjoon] 백준 11724번 : 연결 요소의 개수 (by python) dfs,bfs (0) | 2022.06.14 |
[baekjoon] 백준 11723번 : 집합 (by python) set (0) | 2022.06.13 |