๋ฐฑ์ค 10026, 4963๋ฒ ํ์ด์ฌ
import sys
from collections import deque
input = sys.stdin.readline
n = int(input())
color = []
result_1 = []
for _ in range(n):
color.append(list(input().strip()))
visted_1 = [[False] * n for _ in range(n)]
# ์์ฝ ์๋ ์ฌ๋์ ๋ฐฉ๋ฌธ๊ธฐ๋ก
visted_2 = [[False] * n for _ in range(n)]
# ์์ฝ ์๋ ์ฌ๋์ ๋ฐฉ๋ฌธ๊ธฐ๋ก
move = ((0,1), (0, -1), (1, 0), (-1, 0)) # (์ข, ์ฐ, ํ, ์)
cnt_1, cnt_2 = 0, 0
for i in range(n):
for j in range(n):
if (not visted_1[i][j]):
cnt_1 += 1
c = color[i][j]
q = deque([(i,j)])
visted_1[i][j] = True
while q: # bfs
ci, cj = q.popleft()
for mi, mj in move:
xi,xj = (ci + mi), (cj + mj)
if (0<=xi<n) and (0<=xj<n) and (not visted_1[xi][xj]) and color[xi][xj] == c:
# n x m ๋ฒ์ ์ ์ํ์ข์ฐ ๋ด์ ๋ฐฉ๋ฌธํ์ง ์์ ๊ณณ ์ค์
# ๊ฐ์ ์์ ๊ฐ์ง ๋ถ๋ถ์ด ์๋์ง ์ฒดํฌ
q.append((xi,xj))
visted_1[xi][xj] = True
umm = ('R', 'G') # ์์ฝ์ธ์๊ฒ๋ R๊ณผ G๊ฐ ๋์ผ ๊ฒฝ๋ก๋ก ์ฒดํฌ๋๋ค.
for i in range(n):
for j in range(n):
if (not visted_2[i][j]):
cnt_2 += 1
c = color[i][j]
q = deque([(i,j)])
visted_2[i][j] = True
while q: # bfs
ci, cj = q.popleft()
for mi, mj in move:
xi,xj = (ci + mi), (cj + mj)
if (0<=xi<n) and (0<=xj<n) and (not visted_2[xi][xj]) :
if (c in umm): # R ๋๋ G์ธ ๊ฒฝ์ฐ
# ๋ค์ ๊ฒฝ๋ก์ R or G๊ฐ ์ค๋ฉด ์ด๋ ๊ฐ๋ฅํ๋ค.
if (color[xi][xj] in umm):
q.append((xi,xj))
visted_2[xi][xj] = True
elif color[xi][xj] == c: # B ์ผ๋
q.append((xi,xj))
visted_2[xi][xj] = True
print(cnt_1, cnt_2)
import sys
from collections import deque
input = sys.stdin.readline
n, m = map(int, input().split())
result = []
move = ((0,1), (1,0), (-1, 0), (0, -1), (1,1), (1, -1), (-1, -1), (-1, 1))
# ์ํ์ข์ฐ ๋ง๊ณ ๋๊ฐ์ ์ผ๋ก๋ ์ด๋๊ฐ๋ฅ
while n > 0 and m > 0: # n, m์ด ๋ ๋ค 0์ด ์
๋ ฅ์ผ๋ก ๋ค์ด์ค๋ฉด ๋๋๋ค.
feild = []
visited = [[0] * n for _ in range(m)]
count = 0
for _ in range(m):
feild.append(list(map(int, input().strip().split())))
for i in range(m):
for j in range(n):
if visited[i][j] == 0 and feild[i][j] == 1:
count += 1
q = deque([(i, j)])
visited[i][j] = 1
while q : # bfs
ci, cj = q.popleft()
for mi, mj in move :
xi, xj = (mi + ci), (mj + cj)
if 0<=xi<m and 0<=xj<n and visited[xi][xj] == 0 and feild[xi][xj] == 1:
# ์ด๋๊ฐ๋ฅ ๋ฒ์ ๋ด์ ๋ฐฉ๋ฌธํ์ ์์ผ๋ฉด์ ์กฐ๊ฑด์ ๋ง์กฑํ๋ ๊ฒฝ์ฐ
# ์ด๋๊ฐ๋ฅ ์ฌ์ผ๋ก ๊ฐ์ฃผํ๋ค.
q.append((xi, xj))
visited[xi][xj] = 1
result.append(count)
n, m = map(int, input().split())
for val in result:
print(val)
๋ ๋ฌธ์ ๋ชจ๋ bfs๋ก ํด๊ฒฐํ์์ต๋๋ค.
bfs๊ฐ ์๋ฌด๋๋ ๊ตฌํํ๊ธฐ ๋ ์ฌ์ด ๊ฒ ๊ฐ์ต๋๋ค.