Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

짱이 될거야

백준 1926: 그림 Python (BFS) 본문

알고리즘

백준 1926: 그림 Python (BFS)

짱이 되었어 2022. 10. 12. 14:15

 

 

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)

 

 

Comments