๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 1303 - ์ „์Ÿ - ์ „ํˆฌ

by HandHand 2021. 3. 18.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 1303๋ฒˆ

ํ’€์ด ๊ณผ์ •

๋‘ ์„ธ๋ ฅ๊ฐ„์˜ ๊ทœ๋ชจ๋ฅผ ์ธก์ •ํ•˜๋Š” BFS ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
W ์™€ B ๋กœ ๋‚˜๋ˆ„์–ด์ง„ ์ปดํฌ๋„ŒํŠธ์˜ ํฌ๊ธฐ๋ฅผ ๊ตฌํ•˜๋ฉด ๋˜๋Š”๋ฐ ์ด๋•Œ BFS ๋ฅผ ํ™œ์šฉํ•˜๊ณ 
๊ฐ ์ปดํฌ๋„ŒํŠธ์˜ ํฌ๊ธฐ๋ฅผ ๊ตฌํ• ๋•Œ๋งˆ๋‹ค ์ œ๊ณฑํ•œ ๊ฐ’์„ ์„ธ๋ ฅ ๊ทœ๋ชจ์— ๋”ํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
from collections import deque

N, M = list(map(int, sys.stdin.readline().split()))
board = [list(sys.stdin.readline().strip()) for _ in range(M)]

dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]


def in_range(x, y):
    return 0 <= x < M and 0 <= y < N


def bfs(x, y, visit):
    q = deque()
    check = 0

    q.append([x, y])
    visit[x][y] = 1

    while q:
        x, y = q.popleft()
        check += 1

        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]
            if in_range(nx, ny) and board[nx][ny] == board[x][y] and not visit[nx][ny]:
                q.append([nx, ny])
                visit[nx][ny] = 1

    return check


def solution():
    warrior = {
        'B': [],
        'W': []
    }
    visit = [[0] * N for _ in range(M)]

    for x in range(M):
        for y in range(N):
            if not visit[x][y]:
                size = bfs(x, y, visit)
                warrior[board[x][y]].append(size)

    W = sum(map(lambda x: x**2, warrior['W']))
    B = sum(map(lambda x: x**2, warrior['B']))

    return f"{W} {B}"


print(solution())
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 4195 - ์นœ๊ตฌ ๋„คํŠธ์›Œํฌ  (0) 2021.03.18
BOJ 17626 - Four Squares  (0) 2021.03.18
BOJ 1260 - DFS์™€ BFS  (0) 2021.03.18
BOJ 6550 - ๋ถ€๋ถ„ ๋ฌธ์ž์—ด  (0) 2021.03.18
BOJ 10819 - ์ฐจ์ด๋ฅผ ์ตœ๋Œ€๋กœ  (0) 2021.03.18

๐Ÿ’ฌ ๋Œ“๊ธ€