Algorithm/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€(BOJ) / Python] 10026๋ฒˆ: ์ ๋ก์ƒ‰์•ฝ

meeeeejin 2021. 3. 16. 00:03

๋ฌธ์ œ ๋งํฌ: www.acmicpc.net/problem/10026

 

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

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

www.acmicpc.net

 

๋ฌธ์ œ ์„ค๋ช…

  • ์ ๋ก์ƒ‰์•ฝ์ธ ์‚ฌ๋žŒ๊ณผ ์•„๋‹Œ ์‚ฌ๋žŒ์˜ matrix๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“ค์–ด์„œ ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
  • ์ €๋Š” ์ ๋ก์ƒ‰์•ฝ์˜ matrix๋Š” G๋ฅผ ๋ชจ๋‘ R๋กœ ๋ฐ”๊ฟ”์„œ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค. 
  • ๊ฐ๊ฐ์˜ matrix๋ฅผ BFS๋ฅผ ์ด์šฉํ•ด ์ƒ, ํ•˜, ์ขŒ, ์šฐ๋กœ ์—ฐ๊ฒฐ๋œ ๊ฐ™์€ ์ƒ‰์„ ๋ชจ๋‘ ํƒ์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
  • ์ด๋•Œ ์ƒ, ํ•˜, ์ขŒ, ์šฐ ์ธ๋ฑ์Šค๋ฅผ ํŽธํ•˜๊ฒŒ ๊ณ„์‚ฐํ•˜๊ธฐ ์œ„ํ•ด dx, dy๋ฅผ ์ •์˜ํ•ด์„œ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. 
  • ๋ฐฉ๋ฌธํ•œ matrix์˜ ์›์†Œ๋Š” 0์„ ๋Œ€์ž…ํ•ด์„œ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค๋‹ˆ๋‹ค. 

 

 

์†Œ์Šค์ฝ”๋“œ

import sys
from collections import deque

def bfs(i, j, color, arr):
    queue = deque()
    queue.append((i, j))    # matrix[i][j]๋ถ€ํ„ฐ bfs ์‹œ์ž‘
    arr[i][j] = 0   # ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ

    while queue:
        x, y = queue.popleft()
        for idx in range(4):    # ์ƒ, ํ•˜, ์ขŒ, ์šฐ
            nx = x + dx[idx]
            ny = y + dy[idx]
            # ์ธ๋ฑ์Šค๊ฐ€ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๋Š” ๊ฒฝ์šฐ
            if nx < 0 or nx >= n or ny < 0 or ny >= n:
                continue
            # ๊ฐ™์€ ์ƒ‰์ผ ๊ฒฝ์šฐ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌํ•˜๊ณ  queue์— ๋„ฃ๊ธฐ
            if arr[nx][ny] == color:
                arr[nx][ny] = 0
                queue.append((nx, ny))


# ์ƒ, ํ•˜, ์ขŒ, ์šฐ
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

n = int(sys.stdin.readline())
matrix = [list(sys.stdin.readline()) for _ in range(n)] # ์ ๋ก์ƒ‰์•ฝ ์•„๋‹Œ
matrix_rg = [[0] * n for _ in range(n)]    # ์ ๋ก์ƒ‰์•ฝ

# ์ ๋ก์ƒ‰์•ฝ์˜ matrix(์ดˆ๋ก์ƒ‰์„ ๋ชจ๋‘ ๋นจ๊ฐ„์ƒ‰์œผ๋กœ ๋ฐ”๊ฟˆ)
for i in range(n):
    for j in range(n):
        if matrix[i][j] == 'R' or matrix[i][j] == 'G':
            matrix_rg[i][j] = 'R'
        else:
            matrix_rg[i][j] = 'B'

answer = 0
answer_rg = 0
for i in range(n):
    for j in range(n):
        # ์ ๋ก์ƒ‰์•ฝ ์•„๋‹Œ ์‚ฌ๋žŒ
        if matrix[i][j] != 0:
            bfs(i, j, matrix[i][j], matrix)
            answer += 1
        # ์ ๋ก์ƒ‰์•ฝ์ธ ์‚ฌ๋žŒ
        if matrix_rg[i][j] != 0:
            bfs(i, j, matrix_rg[i][j], matrix_rg)
            answer_rg += 1
            
print(answer, answer_rg)

 

 

 

728x90