λ¬Έμ
λ°±μ€ μ¨λΌμΈ μ μ§ - 7562λ²
νμ΄ κ³Όμ
λμ΄νΈκ° μ΄λν μ μλ λ°©ν₯μ ν΅ν΄ λͺ©ν μ§μ μ λλ¬νλ μ΅μ μ΄λ νμλ₯Ό μ°Ύμμ£Όλ λ¬Έμ μ
λλ€.
μ΄λν μ μλ λ°©ν₯μ΄ 8κ°μ§λΌλ μ μ μ μΈνλ©΄ μΌλ°μ μΈ BFS
νμ νμ΄λ²μΌλ‘ ν΄κ²°ν μ μμ΅λλ€.
μ½λ
import sys
from collections import deque
T = int(input())
test_case = []
for _ in range(T):
L = int(input())
cur = list(map(int, sys.stdin.readline().split()))
goal = list(map(int, sys.stdin.readline().split()))
test_case.append([L, cur, goal])
dx = [-1, -2, -2, -1, 1, 2, 2, 1]
dy = [-2, -1, 1, 2, -2, -1, 1, 2]
def bfs(L, start, goal):
q = deque()
visit = [[False] * L for _ in range(L)]
visit[start[0]][start[1]] = True
q.append((start[0], start[1], 0))
while q:
x, y, cost = q.popleft()
if x == goal[0] and y == goal[1]:
return cost
for i in range(8):
next_x, next_y = x + dx[i], y + dy[i]
if 0 <= next_x < L and 0 <= next_y < L and not visit[next_x][next_y]:
visit[next_x][next_y] = True
q.append((next_x, next_y, cost + 1))
def solution():
for case in test_case:
print(bfs(case[0], case[1], case[2]))
solution()
λ°μν
'π algorithm > boj' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
BOJ 1654 - λμ μλ₯΄κΈ° (0) | 2021.03.18 |
---|---|
BOJ 3184 - μ (0) | 2021.03.18 |
BOJ 18352 - νΉμ 거리μ λμ μ°ΎκΈ° (0) | 2021.03.18 |
BOJ 16173 - μ νμ 쩰리(small) (0) | 2021.03.18 |
BOJ 2096 - λ΄λ €κ°κΈ° (0) | 2021.03.18 |
π¬ λκΈ