DevYoon

[๋ฐฑ์ค€] 10026. ์ ๋ก์ƒ‰์•ฝ (Python) ๋ณธ๋ฌธ

PS/Baekjoon

[๋ฐฑ์ค€] 10026. ์ ๋ก์ƒ‰์•ฝ (Python)

gimewn 2022. 5. 11. 19:35

link ๐Ÿ”— https://www.acmicpc.net/problem/10026

 

10026๋ฒˆ: ์ ๋ก์ƒ‰์•ฝ

์ ๋ก์ƒ‰์•ฝ์€ ๋นจ๊ฐ„์ƒ‰๊ณผ ์ดˆ๋ก์ƒ‰์˜ ์ฐจ์ด๋ฅผ ๊ฑฐ์˜ ๋Š๋ผ์ง€ ๋ชปํ•œ๋‹ค. ๋”ฐ๋ผ์„œ, ์ ๋ก์ƒ‰์•ฝ์ธ ์‚ฌ๋žŒ์ด ๋ณด๋Š” ๊ทธ๋ฆผ์€ ์•„๋‹Œ ์‚ฌ๋žŒ์ด ๋ณด๋Š” ๊ทธ๋ฆผ๊ณผ๋Š” ์ข€ ๋‹ค๋ฅผ ์ˆ˜ ์žˆ๋‹ค. ํฌ๊ธฐ๊ฐ€ N×N์ธ ๊ทธ๋ฆฌ๋“œ์˜ ๊ฐ ์นธ์— R(๋นจ๊ฐ•), G(์ดˆ๋ก)

www.acmicpc.net

 

โœ๏ธ 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)