๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 20005๋ฒ
ํ์ด ๊ณผ์
ํด๋น ๋ฌธ์ ๋ pypy3๋ก ํ์ดํ์ต๋๋ค.
๋ชฌ์คํฐ์ ํ๋ ์ด์ด์ ์์น๊ฐ ์ฃผ์ด์ง ๋ ๋ชฌ์คํฐ๋ฅผ ์ฒ์นํด์ ๋ณด์์ ์ป์ ์ ์๋ ํ๋ ์ด์ด์ ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์
๋๋ค.
ํ๋ ์ด์ด๋ ๋ชฌ์คํฐ์๊ฒ ์ต๋จ ๊ฑฐ๋ฆฌ๋ก ์ด๋ํ๊ธฐ ๋๋ฌธ์ BFS
๋ฅผ ์ด์ฉํด์ ๋ชฌ์คํฐ ๊น์ง์ ์ต๋จ ๊ฒฝ๋ก๋ฃฐ ๊ตฌํ๋ฉด ๋ฉ๋๋ค.
์ด๋ ์ํ๊ณต๊ฐ S
๋ ๋ค์๊ณผ ๊ฐ์ด ์ ์ํ ์ ์์ต๋๋ค.
S[x][y][player] = (x, y) ์ง์ ์ player ๊ฐ ์ด๋ฏธ ๋ฐฉ๋ฌธํ ์ ์ด ์๋์ง ์ ๋ฌด
ํ ๊ฐ์ง ์ค์๋ฅผ ํ๋ ์ ์ `BFS` ๊ฐ ์ข ๋ฃ๋๊ธฐ ์ํ ์กฐ๊ฑด์ผ๋ก `queue` ๊ฐ ๋น์ด์๋์ง๋ฅผ ์ฒดํฌํ ๊ฒ์ธ๋ฐ,
์ฌ์ค ๋ ์ด์ ์ด๋ํ ๊ณณ์ด ์๋๋ผ๋ ๋ชฌ์คํฐ์ ์ฒด๋ ฅ์ด 0 ์ดํ๊ฐ ๋ ๋๊น์ง ๊ฒ์์ ์งํํด์ผํด์ ๊ณ์ ํ๋ ธ์์ต๋๋ค.
๋ฐ๋ผ์ ์ด ๋ถ๋ถ๋ง ์ ์ํด์ ๋ฌธ์ ๋ฅผ ํ๋ฉด ๋ ๊ฒ ๊ฐ์ต๋๋ค.
์ฝ๋
import sys
from collections import deque
from functools import reduce
M, N, P = list(map(int, sys.stdin.readline().split()))
board = [list(sys.stdin.readline().strip()) for _ in range(M)]
powers = {}
player_indices = {}
for idx in range(P):
player, power = list(sys.stdin.readline().split())
powers[player] = int(power)
player_indices[player] = idx
HP = int(input())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def pre_processing(board):
positions = []
for x in range(M):
for y in range(N):
if 'a' <= board[x][y] <= 'z':
positions.append([x, y, board[x][y]])
return positions
def bfs(positions):
global HP
q = deque()
visit = [[[0] * P for _ in range(N)] for _ in range(M)]
arrived = []
for x, y, player in positions:
q.append([x, y, player])
visit[x][y][player_indices[player]] = 1
while HP > 0:
loop = len(q)
for _ in range(loop):
x, y, player = q.popleft()
player_idx = player_indices[player]
if board[x][y] == 'B':
arrived.append(player)
continue
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < M and 0 <= ny < N:
if board[nx][ny] != 'X' and not visit[nx][ny][player_idx]:
q.append([nx, ny, player])
visit[nx][ny][player_idx] = 1
# ๋ชฌ์คํฐ ๊ณต๊ฒฉ
if len(arrived):
HP -= reduce(lambda acc, p: acc + powers[p], arrived, 0)
return len(arrived)
def solution():
positions = pre_processing(board)
answer = bfs(positions)
return answer
print(solution())
๋ฐ์ํ
'๐ algorithm > boj' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ 14496 - ๊ทธ๋, ๊ทธ๋จธ๊ฐ ๋์ด (0) | 2021.03.16 |
---|---|
BOJ 9311 - Robot in a Maze (0) | 2021.03.14 |
BOJ 17521 - Byte Coin (0) | 2021.03.14 |
BOJ 20363 - ๋น๊ทผ ํค์ฐ๊ธฐ (0) | 2021.03.14 |
BOJ 14588 - Line Friends (Small) (0) | 2021.03.14 |
๐ฌ ๋๊ธ