ํฐ์คํ ๋ฆฌ ๋ทฐ
๋ฌธ์
๋ฌธ์ ํ์ด
์์ ๋ค๋ฃฌ ๋ฌธ์ ์ธ ๊ตฌ์ฌ ํ์ถ์ ์ดํดํ๊ณ ์๋ค๋ฉด, ์ฝ๊ฒ ํ ์ ์๋ ๋ฌธ์ ์ด๋ค. ์ด์ ์ ๋ฌธ์ ์ ๋ค๋ฅธ ์ ์ด ์๋ค๋ฉด ๊ตฌ์ฌ ํ์ถ 2์ ๋ฌธ์ ์์ ์ด๋ ๊ฒฝ๋ก๋ ํจ๊ป ์ถ๋ ฅํ๋ ๊ฒ์ด๋ค. visited์ ๊ฒฝ์ฐ ๋จ์ํ ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ์ฒดํฌํ๋ False / True ํํ๋ก ์ ์ธํ ์๋ ์์ง๋ง, visited๋ฅผ ๋ฌธ์๋ก ์ ์ธํ๊ฒ ๋๋ฉด ๊ฐ ๋ฐฉ๋ฌธ์ ๋ฐ๋ผ ๋ฐฉ๋ฌธ ๊ฒฝ๋ก๋ฅผ ํ์ธํ ์ ์๋ค.
dirs = {'R': (0, 1), 'L': (0, -1), 'D': (1, 0), 'U': (-1, 0)}
๊ธฐ์ธ์ธ ๋ฐฉํฅ์ ๋ฐ๋ผ, ๊ฒฝ๋ก๋ฅผ ์ถ์ ํ๊ธฐ ์ํด ๋์ ๋๋ฆฌ๋ฅผ ํ์ฉํ์ฌ ๋ฐฉํฅ ํ์์ ์งํํ๋ฉด ์ฝ๊ฒ ์ฒ๋ฆฌํ ์ ์๋ค.
์ฝ๋
from sys import stdin
from collections import deque
def move_beads(loc, dx, dy):
cnt = 0
while graph[loc[X] + dx][loc[Y] + dy] != '#':
if graph[loc[X]][loc[Y]] == 'O':
break
loc = [loc[X] + dx, loc[Y] + dy]
cnt += 1
return loc, cnt
def bfs(start):
q = deque([start])
dirs = {'R': (0, 1), 'L': (0, -1), 'D': (1, 0), 'U': (-1, 0)}
while q:
r, b, cnt = q.popleft()
path = visited[r[X]][r[Y]][b[X]][b[Y]]
if cnt > 10:
break
for move in dirs:
dx, dy = dirs[move]
next_path = path + move
next_red, red_cnt = move_beads(r, dx, dy)
next_blue, blue_cnt = move_beads(b, dx, dy)
# ํ๋์ ๊ตฌ์ฌ์ด ๋จผ์ ํ์ถํ๋ ๊ฒฝ์ฐ์ ์ ์ ์ธ.
if graph[next_blue[X]][next_blue[Y]] == 'O':
continue
# ๋นจ๊ฐ ๊ตฌ์ฌ์ด ๋จผ์ ํ์ถ ๊ฐ๋ฅํ ๊ฒฝ์ฐ
if graph[next_red[X]][next_red[Y]] == 'O':
# ๊ตฌ์ฌ์ ์ฐพ์ ๊ฒฝ์ฐ
# ์๋ ํ์, INIT ๋ฌธ์๋ฅผ ์ ์ธํ ๋๋จธ์ง๋ฅผ ๋ฐํ.
return cnt, next_path[4:]
if next_red == next_blue:
if red_cnt > blue_cnt:
next_red = [next_red[X] - dx, next_red[Y] - dy]
else:
next_blue = [next_blue[X] - dx, next_blue[Y] - dy]
r_x, r_y = next_red; b_x, b_y = next_blue
if not visited[r_x][r_y][b_x][b_y]:
visited[r_x][r_y][b_x][b_y] = next_path
q.append([[r_x, r_y], [b_x, b_y], cnt + 1])
return -1, None
if __name__ == '__main__':
X, Y = 0, 1
n, m = map(int, stdin.readline().split())
graph = []
red = blue = None
for i in range(n):
graph.append(list(stdin.readline().strip()))
if red is None and 'R' in graph[i]:
red = [i, graph[i].index('R')]
if blue is None and 'B' in graph[i]:
blue = [i, graph[i].index('B')]
visited = \
[[[[''] * m for _ in range(n)] for _ in range(m)] for _ in range(n)]
visited[red[X]][red[Y]][blue[X]][blue[Y]] = 'INIT'
for ret in bfs([red, blue, 1]):
if ret is not None:
print(ret)
์ด๊ธฐ์ ๋นจ๊ฐ ๊ตฌ์ฌ, ํ๋ ๊ตฌ์ฌ์ ๊ฒฝ๋ก(์์์ )์ ์ฌ๋ฐฉ๋ฌธ ํ์ง ์๊ธฐ ์ํด, ํด๋น ์ขํ๋ฅผ INIT๋ก ์ด๊ธฐํ ํ์๋ค. ๋ฐ๋ผ์ ํ์ถ ๊ฐ๋ฅํ ๊ฒฝ์ฐ์๋ INIT๋ฅผ ์ ์ธํ ๋๋จธ์ง ๊ฒฝ๋ก๋ฅผ ์ถ๋ ฅํ์ฌ์ผ ํ๋ค.
'๐จโ๐ป ์ฝ๋ฉํ ์คํธ > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค: 2225 ํฉ๋ถํด (0) | 2020.08.12 |
---|---|
๋ฐฑ์ค: 3055 ํ์ถ (0) | 2020.08.11 |
๋ฐฑ์ค: 13459 ๊ตฌ์ฌ ํ์ถ (0) | 2020.08.07 |
๋ฐฑ์ค: 1987 ์ํ๋ฒณ (0) | 2020.08.06 |
๋ฐฑ์ค: 16198 ์๋์ง ๋ชจ์ผ๊ธฐ (0) | 2020.08.06 |