๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 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()
๋ฐ์ํ
'๐ algorithm > boj' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ 13908 - ๋น๋ฐ๋ฒํธ (0) | 2021.04.13 |
---|---|
BOJ 14940 - ์ฌ์ด ์ต๋จ๊ฑฐ๋ฆฌ (0) | 2021.04.13 |
BOJ 1922 - ๋คํธ์ํฌ ์ฐ๊ฒฐ (0) | 2021.04.13 |
BOJ 20006 - ๋ญํน์ ๋๊ธฐ์ด (0) | 2021.04.13 |
BOJ 2869 - ๋ฌํฝ์ด๋ ์ฌ๋ผ๊ฐ๊ณ ์ถ๋ค (0) | 2021.04.13 |
๐ฌ ๋๊ธ