https://www.acmicpc.net/problem/1926
1926번: 그림
어떤 큰 도화지에 그림이 그려져 있을 때, 그 그림의 개수와, 그 그림 중 넓이가 가장 넓은 것의 넓이를 출력하여라. 단, 그림이라는 것은 1로 연결된 것을 한 그림이라고 정의하자. 가로나 세로
www.acmicpc.net
아이디어
bfs/dfs 문제였다. 방향 벡터와 bfs를 사용하여 풀었다.
전체 코드
from collections import deque
n, m = map(int, input().split())
paint = [[ int(x) for x in input().split()] for _ in range(n)]
visited = [[0]*m for _ in range(n)]
def bfs(x, y, paint, visited):
queue = deque([(x, y)])
visited[x][y] = 1
size = 1
dv = [(0,1), (0,-1), (1,0), (-1,0)]
while queue:
x, y = queue.popleft()
for dx, dy in dv:
nx = x + dx
ny = y + dy
if nx < 0 or nx >= n or ny < 0 or ny >= m or visited[nx][ny] == 1 or paint[nx][ny] == 0:
continue
else:
visited[nx][ny] = 1
size += 1
queue.append((nx, ny))
return size
count = 0
max_size = 0
for x in range(n):
for y in range(m):
if paint[x][y] == 1 and visited[x][y] == 0:
max_size = max(bfs(x,y,paint,visited), max_size)
count += 1
print(count)
print(max_size)
'Coding Test > Python' 카테고리의 다른 글
[백준/그리디] 1449번: 수리공 항승 (실버3, python) (0) | 2024.03.13 |
---|---|
[백준/구현&정렬] 8978번: 올림픽 (python, 실버5 ) (0) | 2024.03.12 |
[백준/union-find] 1717번: 집합의 표현(골드5, python) (0) | 2024.02.15 |
[LeetCode] 47. Permutations II (Medium, Python) (1) | 2024.02.14 |
[LeetCode] 46. Permutations (Medium, Python) (0) | 2024.02.14 |