짱이 될거야
백준 1926: 그림 Python (BFS) 본문
from collections import deque
import sys
input = sys.stdin.readline
def bfs(si, sj, total):
global result
# 초기조건
q = deque()
q.append((si, sj))
visited[si][sj] = 1
arr[si][sj] = 2
# 반복조건
while q:
ci, cj = q.popleft()
for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
ni, nj = ci+di, cj+dj
if 0 <= ni < N and 0 <= nj < M:
if arr[ni][nj] == 1 and not visited[ni][nj]:
visited[ni][nj] = 1
total += arr[ni][nj]
arr[ni][nj] = 2
q.append((ni, nj))
if total > result:
result = total
N, M = map(int, input().split()) # N: 행, M: 열
arr = [list(map(int, input().split())) for _ in range(N)] # arr: 도화지
result = 0
cnt = 0
visited = [[0] * M for _ in range(N)]
for i in range(N):
for j in range(M):
if arr[i][j] == 1:
cnt += 1
bfs(i, j, 1)
print(cnt)
print(result)
'알고리즘' 카테고리의 다른 글
백준 2583: 영역 구하기 Python (DFS, BFS) (0) | 2022.10.13 |
---|---|
백준 2667: 단지번호붙이기 Python (DFS, BFS) (0) | 2022.10.13 |
백준 2644: 촌수계산 Python (DFS, BFS) (0) | 2022.10.12 |
백준 14888: 연산자 끼워넣기 Python (순열, DFS) (0) | 2022.10.11 |
프로그래머스: 최솟값 만들기 (0) | 2022.10.10 |
Comments