DevYoon
[๋ฐฑ์ค] 10026. ์ ๋ก์์ฝ (Python) ๋ณธ๋ฌธ
link ๐ https://www.acmicpc.net/problem/10026
โ๏ธ BFS
- ์ ๋ก์์ฝ์ธ ์ฌ๋์ด ๋ณด์์ ๋์ ์ ๋ก์์ฝ์ด ์๋ ์ฌ๋์ด ๋ณด์์ ๋์ ๊ตฌ์ญ ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์
- ์ ๋ก์์ฝ์ผ ๋์ ์๋ ๋๋ฅผ ๊ตฌ๋ถํ์ฌ 2๊ฐ์ visit ๋ฐฐ์ด๊ณผ count, BFS ํจ์๋ฅผ ๋ง๋ค์ด ์ฃผ์๋ค.
- ์ด์คfor๋ฌธ์ผ๋ก visit์ ์ฒดํฌ๊ฐ ๋์ง ์์์ ๋ BFS๋ฅผ ๋๋ฆฌ๋๋ฐ, rgBfs(์ ๋ก์์ฝ BFS)๋ ์์ด R์ด๊ฑฐ๋ G์ผ ๋๋ง ๋๋ ค์ฃผ์๋ค.
- ๋ง์ฝ ํ์ฌ ์์์ด "B"๋ผ๋ฉด ์ ๋ก์์ฝ ์ ๋ฌด๊ฐ ์ํฅ์ ์ฃผ์ง ์์ผ๋ฏ๋ก, ์ผ๋ฐ bfs์์ count์ rgCount๋ฅผ ๋ชจ๋ ์ฆ๊ฐ์์ผ์ฃผ์๋ค.
- rgBfs์์๋ ํ์ฌ ์์๊ณผ ์ด๋ํ ๊ณณ์ ์์์ด ๊ฐ์ ๊ฒฝ์ฐ ์ธ์๋ ํ์ฌ ์์์ด R์ด๋ฉด ์ด๋ํ ๊ณณ ์์์ด G์ผ ๋, ํ์ฌ ์์์ด G์ด๋ฉด ์ด๋ํ ๊ณณ ์์์ด R์ธ ๊ฒฝ์ฐ์๋ deque์ ์ฝ์ ์์ผ์ฃผ์๋ค.
from collections import deque
n = int(input())
board = [list(input()) for _ in range(n)]
visit = [[0]*n for _ in range(n)]
rgVisit = [[0]*n for _ in range(n)]
count = 0
rgCount = 0
def bfs(y, x):
global count, rgCount
q = deque()
q.append((y, x, board[y][x]))
visit[y][x] = 1
while q:
nowy, nowx, nowchr = q.popleft()
dir = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for y, x in dir:
dy = nowy+y
dx = nowx+x
if 0 <= dy < n and 0 <= dx < n and nowchr == board[dy][dx] and visit[dy][dx] != 1:
visit[dy][dx] = 1
q.append((dy, dx, nowchr))
if nowchr == 'B':
count += 1
rgCount += 1
else:
count += 1
def rgBfs(y, x):
global rgCount
rgQ = deque()
rgQ.append((y, x, board[y][x]))
rgVisit[y][x] = 1
while rgQ:
nowy, nowx, nowchr = rgQ.popleft()
dir = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for y, x in dir:
dy = nowy + y
dx = nowx + x
if 0 <= dy < n and 0 <= dx < n and rgVisit[dy][dx] != 1:
if nowchr == board[dy][dx]:
rgVisit[dy][dx] = 1
rgQ.append((dy, dx, nowchr))
else:
if (nowchr == 'R' and board[dy][dx] == 'G') or (nowchr == 'G' and board[dy][dx] == 'R'):
rgVisit[dy][dx] = 1
rgQ.append((dy, dx, board[dy][dx]))
rgCount += 1
for y in range(n):
for x in range(n):
if visit[y][x] != 1:
bfs(y, x)
if board[y][x] != 'B' and rgVisit[y][x] != 1:
rgBfs(y, x)
print(count, rgCount)