https://www.acmicpc.net/problem/6087
6087번: 레이저 통신
크기가 1×1인 정사각형으로 나누어진 W×H 크기의 지도가 있다. 지도의 각 칸은 빈 칸이거나 벽이며, 두 칸은 'C'로 표시되어 있는 칸이다. 'C'로 표시되어 있는 두 칸을 레이저로 통신하기 위해서
www.acmicpc.net
백준 - 레이저 통신 (Laserphones) (6087번)
난이도 : Gold 3
알고리즘&자료구조 : BFS (너비 우선 탐색) & Simulation (구현)
★ 핵심 Idea ★
첫 번째 소부터 특정 좌표까지 통신하는데 필요한 거울의 개수를 BFS로 구하면서,
두 번째 소까지 이동하면 된다.

< 전체 코드 >
import sys
input = sys.stdin.readline
class Pasture():
def __init__(self, W, H):
board = [list(input().rstrip()) for _ in range(H)]
queue = []
for h in range(H):
for w in range(W):
if board[h][w] == 'C':
queue.append((h, w))
goal = queue.pop()
dd = ((1, 0), (-1, 0), (0, 1), (0, -1))
cnt = flag = 0
tmp = []
while True:
while queue:
ch, cw = queue.pop()
for i in range(4):
dh, dw = dd[i]
ph, pw = ch+dh, cw+dw
while 0 <= ph < H and 0 <= pw < W:
if (ph, pw) == goal:
flag = True
self.mirrors = cnt
break
if board[ph][pw] == '.':
board[ph][pw] = cnt
tmp.append((ph, pw))
ph, pw = ph+dh, pw+dw
elif board[ph][pw] == cnt:
ph, pw = ph+dh, pw+dw
else:
break
if flag:
break
if flag:
break
board[ch][cw] = '*'
if flag:
break
queue = tmp
tmp = []
cnt += 1
if __name__ == '__main__':
pasture = Pasture(*map(int, input().split()))
print(pasture.mirrors)
'Algorithm' 카테고리의 다른 글
돌 그룹 (12886번) - 백준 (BOJ) (0) | 2023.09.03 |
---|---|
소가 길을 건너간 이유 4 (14464번) - 백준 (BOJ) (0) | 2023.09.01 |
좋다 (1253번) - 백준 (BOJ) (0) | 2023.08.30 |
숫자 게임 (2923번) - 백준 (BOJ) (0) | 2023.08.29 |
쓰레기 치우기 (1736번) - 백준 (BOJ) (0) | 2023.08.26 |