2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여
www.acmicpc.net
bfs 방법으로 풀었다.
Python code
더보기
def bfs(n, head, matrix):
dx=[0,0,1,-1] #위 아래 오른쪽 왼쪽
dy=[1,-1,0,0]
cnt=0
queue=[head]
while queue:
cnt+=1
head=queue.pop(0)
matrix[head[0]][head[1]]=0
for i in range(4):
x=head[0]+dx[i]
y=head[1]+dy[i]
if x>-1 and x<n and y>-1 and y<n and matrix[x][y]==1:
queue.append([x,y])
matrix[x][y]=0
return cnt
n=int(input())
matrix=[]
for _ in range(n):
matrix.append(list(map(int,list(input()))))
ans=[]
for i in range(n):
for j in range(n):
if matrix[i][j]==1:
ans.append(bfs(n, [i,j], matrix))
ans.sort()
print(len(ans))
for a in ans:
print(a)
'baekjoon' 카테고리의 다른 글
[백준/BOJ] 1003번 피보나치 함수 (Python) (0) | 2021.02.02 |
---|---|
[백준/BOJ] 1697번 숨바꼭질 (Python) (0) | 2021.01.30 |
[백준/BOJ] 1260번 DFS와 BFS (Python) (0) | 2021.01.30 |
[백준/BOJ] 15711번 환상의 짝꿍 (Python) (0) | 2021.01.30 |
[백준/BOJ] 6588번 골드바흐의 추측 (Python) (0) | 2021.01.30 |