https://www.acmicpc.net/problem/2667
2667번 문제는 저번에도 풀어봤고 이번에 다시 복습해보았다.
확실히 한 번 풀었어서 그런지 빨리 풀렸다.
import sys
input = sys.stdin.readline
#bfs
dy=[0,1,-1,0]
dx=[-1,0,0,1]
def bfs(y,x,res):
cnt=0
queue=[[y,x]]
while queue:
cnt+=1
curr=queue.pop(0)
for d in range(4):
ny=dy[d]+curr[0]
nx=dx[d]+curr[1]
if 0<=ny<N and 0<=nx<N:
if graph[ny][nx]==1:
queue.append([ny,nx])
graph[ny][nx]=0
res.append(cnt)
#1.입력
N=int(input())
graph=[]
for _ in range(N):
graph.append(list(map(int,input().strip())))
res=[] #정답리스트
cnt=0 #전단지 붙은 단지
#2.자료형 정의
#3.함수 정의
for i in range(N):
for j in range(N):
if graph[i][j]==1:
graph[i][j]=0
bfs(i,j,res)
cnt+=1
#4.출력
print(cnt)
res=sorted(res)
for r in res:
print(r)
저번에 풀 때는 입력을 문자열로 받아서 문자열 '1'과 '0'으로 하였는데
graph.append(list(map(int,input())))
이런 식으로 입력을 받게 되면 공백 없는 숫자들의 입력값이더라도 리스트 값으로 만들 수 있었다.
입력을 더 빨리하기 위해 realine() 메서드를 추가해주었는데 오류가 발생하였다.
graph.append(list(map(int,input().strip())))
.strip()를 추가해주니 해결되었다.
'coding test > Baekjoon' 카테고리의 다른 글
| [Python] 24444번 알고리즘 수업 - 너비 우선 탐색 1 (0) | 2025.04.23 |
|---|---|
| [Python] 11724번 연결 요소의 개수 (0) | 2025.04.23 |
| [Python] 2210번 숫자판 점프 (0) | 2025.04.13 |
| [Python] 4963번 섬의 개수 / DFS.ver (0) | 2025.04.13 |
| [Python] 2583번 영역 구하기 / DFS (0) | 2025.04.13 |