๋ฌธ์
ํ์ด
๋นํธ ๋ง์คํน์ ์ฌ์ฉํด ํ์๋ค.
์์ง ๋ฐฉ๋ฌธํ์ง ์์ ์ํ : 0b0
ํค ์์ : 0b1
aํค : 0b10
bํค : 0b100
cํค : 0b1000
a, cํค : 0b1010
...
์ด๋ฐ ์์ผ๋ก ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ๊ธฐ๋กํ๋ค.
๋ํ haveKey์ ๋ฏผ์์ด๊ฐ ๋ณด์ ํ ์ด์ ์ ๋ณด๋ฅผ ๋นํธ ๋ง์คํนํ๋ค.
ํค ์์ : 0b1
aํค ๋ณด์ : 0b11
bํค ๋ณด์ : 0b101
a, bํค ๋ณด์ : 0b111
...
๋ง์ฝ a, bํค๋ฅผ ๊ฐ์ง ๋ฏผ์์ด๊ฐ ์ขํ(x, y)์ ๋ฐฉ๋ฌธํ๋ ค ํ๋ค.
ํ์ง๋ง ํด๋น ์ขํ์ ์ด๋ฏธ a, b, cํค๋ฅผ ์์ ํ ์ฑ๋ก ๋ฐฉ๋ฌธํ ์ ์ด ์๋ค๋ฉด ๋ฐฉ๋ฌธํ ํ์๊ฐ ์๋ค.
if (visited[ni][nj] | haveKey) == visited[ni][nj]: continue
์๋ ๋งํฌ๋ฅผ ์ฐธ๊ณ ํ๋ฉด ์ดํดํ๊ธฐ ์ฝ๋ค.
https://studyandwrite.tistory.com/325
์ฝ๋
import sys
from collections import deque
input = sys.stdin.readline
key = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
door = {'A':1, 'B':2, 'C':3, 'D':4, 'E':5, 'F':6}
n, m = map(int, input().split())
graph = [list(input().rstrip()) for _ in range(n)]
visited = [[0] * m for _ in range(n)]
def condition(ni, nj):
return ni < 0 or ni >= n or nj < 0 or nj >= m or graph[ni][nj] == '#'
def bfs(y, x):
q = deque()
q.append((y, x, 1, 0))
visited[y][x] |= (1 << 0)
dir = ((0, 1), (0, -1), (1, 0), (-1, 0))
while q:
i, j, haveKey, cnt = q.popleft()
if graph[i][j] == '1':
print(cnt)
return
for dy, dx in dir:
ni, nj = i + dy, j + dx
if condition(ni, nj): continue
if (visited[ni][nj] | haveKey) == visited[ni][nj]: continue
if 'A' <= graph[ni][nj] <= 'F':
if not (haveKey & (1 << door[graph[ni][nj]])): #ํค๊ฐ ์๋ ๊ฒฝ์ฐ
continue
if 'a' <= graph[ni][nj] <= 'f':
q.append((ni, nj, haveKey | (1 << key[graph[ni][nj]]), cnt + 1))
visited[ni][nj] = (haveKey | (1 << key[graph[ni][nj]]))
continue
q.append((ni, nj, haveKey, cnt + 1))
visited[ni][nj] = haveKey
print(-1)
for i in range(n):
for j in range(m):
if graph[i][j] == '0':
bfs(i, j)
break
๋ง๋ฌด๋ฆฌ
๊ณจ๋ 1 ๋ฌธ์ ์ฌ์ ๋ง์ด ์ซ์๋๋ฐ ์๊ฐ๋ณด๋ค ํ๋ง ํ๋ค. (๋ฐฉ๋ฌธ ์ฒ๋ฆฌ์์ ์๊ฐ์ ๊ฝค ์ก์๋จน๊ธด ํ์ง๋ง...)
๋ ธ๋๊ฐ ์์ฒญ ์ข๋ค ใ
https://www.youtube.com/watch?v=wG2lDphHVR8