λ¬Έμ
λ°±μ€ μ¨λΌμΈ μ μ§ - 16509λ²
νμ΄ κ³Όμ
μ
μ΄ μμ§μΌ μ μλ λ°©λ²μ κ³ λ €νμ¬ μ
μκ² λλ¬ κ°λ₯ν μ΅μμκ°μ ꡬνλ λ¬Έμ μ
λλ€.
λ¬Έμ μ μ μλ λ°©λ²μΌλ‘ μ
μ BFS
λ₯Ό μ΄μ©ν΄ μ΅μμκ°μ ꡬν μ μμΌλ©° μ΄λ μ£Όμν μ μ
μμ μ΄λ κ²½λ‘κ° κ²©μλ₯Ό λ²μ΄λκ±°λ λ€λ₯Έ λ¬Όμ²΄κ° μμΌλ©΄ μλλ€λ κ²μ
λλ€.
λ°λΌμ κ²½λ‘μμ λͺ¨λ μ§μ μ νμΈνλ check_path
ν¨μλ₯Ό ꡬννκ³ λ§μ½ ν΅κ³Όν κ²½μ°μλ§
ν΄λΉ μ§μ μΌλ‘ νμμ μ΄μ΄κ°λ λ°©λ²μΌλ‘ ꡬννμ΅λλ€.
μ½λ
import sys
from collections import deque
sang = list(map(int, sys.stdin.readline().split()))
king = list(map(int, sys.stdin.readline().split()))
path_finder = {
0: [[-1, 0], [-1, -1], [-1, -1]],
1: [[-1, 0], [-1, 1], [-1, 1]],
2: [[0, 1], [-1, 1], [-1, 1]],
3: [[0, 1], [1, 1], [1, 1]],
4: [[1, 0], [1, 1], [1, 1]],
5: [[1, 0], [1, -1], [1, -1]],
6: [[0, -1], [1, -1], [1, -1]],
7: [[0, -1], [-1, -1], [-1, -1]],
}
def check_path(x, y, i):
for idx, [dx, dy] in enumerate(path_finder[i]):
x, y = x + dx, y + dy
if x < 0 or x > 9 or y < 0 or y > 8:
return [False, None]
elif idx != 2 and [x, y] == king:
return [False, None]
return [True, [x, y]]
def bfs():
visit = [[0] * 9 for _ in range(10)]
q = deque()
visit[sang[0]][sang[1]] = 1
q.append([*sang, 0])
while q:
x, y, cost = q.popleft()
if [x, y] == king:
return cost
for i in range(8):
is_reachable, next = check_path(x, y, i)
if is_reachable:
nx, ny = next
if not visit[nx][ny]:
visit[nx][ny] = 1
q.append([nx, ny, cost + 1])
return -1
def solution():
answer = bfs()
return answer
print(solution())
λ°μν
'π algorithm > boj' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
BOJ 19941 - νλ²κ±° λΆλ°° (0) | 2021.03.08 |
---|---|
BOJ 16469 - μλ μ ν (0) | 2021.03.05 |
BOJ 13565 - μΉ¨ν¬ (0) | 2021.03.05 |
BOJ 1105 - ν (0) | 2021.03.03 |
BOJ 3190 - λ± (0) | 2021.03.01 |
π¬ λκΈ