코드
import sys
from collections import deque
input = sys.stdin.readline
def bfs(x, y, visited):
q = deque([(x,y)])
size = 1
visited[x][y] = 1
while q:
i, j = q.popleft()
for dir in [(1,0), (0,1), (-1,0), (0,-1)]:
ni, nj = i + dir[0], j + dir[1]
if ni < 0 or nj < 0 or ni >= n or nj >= m: continue
if not visited[ni][nj] and graph[ni][nj] == 1:
q.append((ni, nj))
size += 1
visited[ni][nj] = 1
return size
n, m = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(n)]
visited = [[0]*m for _ in range(n)]
numPic = 0
maxSize = 0
for i in range(n):
for j in range(m):
if not visited[i][j] and graph[i][j] == 1:
size = bfs(i, j, visited)
if (size > maxSize):
maxSize = size
numPic += 1
print(numPic)
print(maxSize)
결과
풀이 방법
BFS
의 개념으로 간단하게 풀이할 수 있는 문제였다.