※ 1926 그림
https://www.acmicpc.net/problem/1926
문제 해결 TIP
bfs로 간단하게 풀 수 있다. 유기농 배추 문제와 비슷하다.
전체 코드
from collections import deque
graph = []
n, m = map(int,input().split())
for i in range(n):
graph.append(list(map(int,input().split())))
#graph = [[1, 1, 0, 1, 1], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0], [1, 0, 1, 1, 1], [0, 0, 1, 1, 1], [0, 0, 1, 1, 1]]
dx = [-1,1,0,0]
dy = [0,0,-1,1]
def bfs(x,y):
graph[x][y] = 0
queue = deque()
queue.append((x, y))
result = 1
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0<= ny < m:
if graph[nx][ny]==1:
queue.append((nx,ny))
graph[nx][ny] = 0
result += 1
return result
count = 0
answer = 0
for i in range(n):
for j in range(m):
if graph[i][j]==1:
count += 1
answer = max(bfs(i,j),answer)
print(count)
print(answer)
'Python > DFS&BFS' 카테고리의 다른 글
[Algorithm] 백준 2665 미로만들기 | 파이썬 BFS (0) | 2024.09.11 |
---|---|
[Algorithm] 백준 7562 나이트의 이동 | 파이썬 BFS (2) | 2024.07.22 |
[Algorithm] 백준 16234 인구 이동 | 파이썬 BFS (1) | 2024.07.03 |
[Algorithm] 백준 18405 경쟁적 전염 | 파이썬 BFS (0) | 2024.07.02 |
[Algorithm] 백준 11724 연결 요소의 개수 | 파이썬 DFS (0) | 2024.06.30 |
댓글