[파이썬] 백준 1926 : 그림 (실버1)
1926번: 그림
어떤 큰 도화지에 그림이 그려져 있을 때, 그 그림의 개수와, 그 그림 중 넓이가 가장 넓은 것의 넓이를 출력하여라. 단, 그림이라는 것은 1로 연결된 것을 한 그림이라고 정의하자. 가로나 세로
www.acmicpc.net
문제
풀이
0. 방향성 생각
- 영역 개수, 넓이 구하기
1. 입력
from collections import deque
import sys
input = lambda : sys.stdin.readline().rstrip()
h,w = map(int,input().split())
arr = [list(map(int,input().split())) for _ in range(h)]
visit = [[False]*w for _ in range(h)]
dire = [(1,0),(0,1),(-1,0),(0,-1)]
2. BFS 함수 정의
def bfs(x,y):
visit[y][x] = True
q = deque([(x,y)])
size = 1
while q:
x,y = q.popleft()
for dx,dy in dire:
nx = x + dx
ny = y + dy
if 0<=nx<w and 0<=ny<h and not visit[ny][nx] and arr[ny][nx] == 1:
visit[ny][nx] = True
q.append((nx,ny))
size += 1
return size
- size 계산해서 리턴해주기
3. 출력
info = []
for i in range(h):
for j in range(w):
if not visit[i][j] and arr[i][j] == 1:
info.append(bfs(j,i))
if info:
print(len(info))
print(max(info))
else:
print(0)
print(0)
- 입력이 500 x 500이라 리스트에 넣는거보다 그냥 최댓값 갱신해주면서 푸는게 나았을듯
전체코드
from collections import deque
import sys
input = lambda : sys.stdin.readline().rstrip()
h,w = map(int,input().split())
arr = [list(map(int,input().split())) for _ in range(h)]
visit = [[False]*w for _ in range(h)]
dire = [(1,0),(0,1),(-1,0),(0,-1)]
def bfs(x,y):
visit[y][x] = True
q = deque([(x,y)])
size = 1
while q:
x,y = q.popleft()
for dx,dy in dire:
nx = x + dx
ny = y + dy
if 0<=nx<w and 0<=ny<h and not visit[ny][nx] and arr[ny][nx] == 1:
visit[ny][nx] = True
q.append((nx,ny))
size += 1
return size
info = []
for i in range(h):
for j in range(w):
if not visit[i][j] and arr[i][j] == 1:
info.append(bfs(j,i))
if info:
print(len(info))
print(max(info))
else:
print(0)
print(0)
코멘트
그림 없는 케이스 빼먹어서 잠깐 삽질함
'Algorithm > Graph' 카테고리의 다른 글
[파이썬] 백준 2982 : 국왕의 방문 (골드2) (0) | 2023.11.22 |
---|---|
[파이썬] 백준 2251: 물통 (골드5) (0) | 2023.11.21 |
[파이썬] 백준 2206 : 벽 부수고 이동하기 (골드3) (0) | 2023.11.16 |
[파이썬] 백준 1303 : 전쟁 - 전투 (실버1) (0) | 2023.11.10 |
[파이썬] 백준 1833 : 고속철도 설계하기 (골드3) (0) | 2023.11.05 |
[파이썬] 백준 2151 : 거울설치 (골드3) (0) | 2023.10.08 |
[파이썬] 백준 1068 : 트리 (골드5) (0) | 2023.09.14 |
댓글