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

BOJ 16441 - ์•„๊ธฐ๋ผ์ง€์™€ ๋Š‘๋Œ€

by HandHand 2021. 4. 13.

๋ฌธ์ œ

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

ํ’€์ด ๊ณผ์ •

BFS ๋ฅผ ์ด์šฉํ•ด์„œ ์•„๊ธฐ๋ผ์ง€๊ฐ€ ์•ˆ์ „ํ•˜๊ฒŒ ์œ„์น˜ํ•  ์ˆ˜ ์žˆ๋Š” ์žฅ์†Œ๋“ค์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
๋ชจ๋“  ๋Š‘๋Œ€๋“ค์˜ ์ดˆ๊ธฐ ์œ„์น˜๋ฅผ ์ฐพ์€ ๋‹ค์Œ, ํ์— ๋„ฃ๊ณ  ์ดˆ๊ธฐํ™”์‹œํ‚ต๋‹ˆ๋‹ค.
์ดํ›„ ๋Š‘๋Œ€๋“ค์„ ๊ธฐ์ค€์œผ๋กœ BFS ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋ฉฐ ๋Š‘๋Œ€๋“ค์ด ๋ฐฉ๋ฌธ ๊ฐ€๋Šฅํ•œ ์œ„์น˜๋ฅผ ํ‘œ์‹œํ•ฉ๋‹ˆ๋‹ค.
๋งŒ์•ฝ ๋Š‘๋Œ€๊ฐ€ ๋น™ํŒ์„ ๋งŒ๋‚œ๋‹ค๋ฉด ์ด๋™์ค‘์ธ ๋ฐฉํ–ฅ์„ ๊ธฐ์ค€์œผ๋กœ ๋ฒฝ์ด๋‚˜ ์ž”๋””๋ฅผ ๋งŒ๋‚ ๋•Œ๊นŒ์ง€ ์ด๋™ํ•ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
from collections import deque


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


def preprocess():
    wolves = []

    for n in range(N):
        for m in range(M):
            if board[n][m] == 'W':
                wolves.append([n, m])

    return wolves


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


def bfs(wolves):
    visit = [[0] * M for _ in range(N)]
    q = deque(wolves)

    for sx, sy in wolves:
        visit[sx][sy] = 1

    while q:
        x, y = q.popleft()

        for direction in range(4):
            nx, ny = x + dx[direction], y + dy[direction]

            while in_range(nx, ny) and board[nx][ny] == '+':
                tx, ty = nx + dx[direction], ny + dy[direction]
                if board[tx][ty] == '+':
                    nx, ny = tx, ty
                elif board[tx][ty] in ['W', '.']:
                    nx, ny = tx, ty
                    break
                else:
                    break

            if in_range(nx, ny) and not visit[nx][ny] and board[nx][ny] != '#':
                visit[nx][ny] = 1
                q.append([nx, ny])

    return visit


def solution():
    wolves = preprocess()
    wolves_visits = bfs(wolves)

    answer = [['.'] * M for _ in range(N)]
    for n in range(N):
        for m in range(M):
            if not wolves_visits[n][m] and board[n][m] == '.':
                answer[n][m] = 'P'
            else:
                answer[n][m] = board[n][m]

    for n in range(N):
        print(''.join(map(str, answer[n])))


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

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

๐Ÿ’ฌ ๋Œ“๊ธ€