1. 테두리검사는 def로 안하는게 좋은듯.
(다른사람꺼 코드)
# 나이트의 이동
# https://www.acmicpc.net/problem/7562
# pypy3 -> 통과
# python3 -> 시간초과
import sys
from collections import deque
input = sys.stdin.readline
adjacent_indices = ((-2, -1), (-1, -2), (1, -2), (2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1))
def is_valid_index(board, r, c):
if r < 0 or c < 0:
return False
if len(board) <= r:
return False
if len(board[r]) <= c:
return False
return True
def solve():
l = int(input())
s_c, s_r = map(int, input().split())
d_c, d_r = map(int, input().split())
if s_c == d_c and s_r == d_r:
return 0
board = [[-1] * l for __ in range(l)]
board[s_r][s_c] = 0
answer = 0
queue = deque()
queue.append((s_r, s_c))
while len(queue) > 0:
cur_r, cur_c = queue.popleft()
for adjacent_index in adjacent_indices:
next_r = cur_r + adjacent_index[0]
next_c = cur_c + adjacent_index[1]
if is_valid_index(board, next_r, next_c):
if board[next_r][next_c] == -1:
board[next_r][next_c] = board[cur_r][cur_c] + 1
if next_r == d_r and next_c == d_c:
return board[next_r][next_c]
queue.append((next_r, next_c))
print(answer)
t = int(input())
for _ in range(t):
answer = solve()
print(answer)
# 나이트의 이동
# https://www.acmicpc.net/problem/7562
import sys
from collections import deque
input = sys.stdin.readline
adjacent_indices = ((-2, -1), (-1, -2), (1, -2), (2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1))
# def is_valid_index(board, r, c):
# if r < 0 or c < 0:
# return False
# if len(board) <= r:
# return False
# if len(board[r]) <= c:
# return False
# return True
def solve():
l = int(input())
s_c, s_r = map(int, input().split())
d_c, d_r = map(int, input().split())
if s_c == d_c and s_r == d_r:
return 0
board = [[-1] * l for __ in range(l)]
board[s_r][s_c] = 0
answer = 0
queue = deque()
queue.append((s_r, s_c))
while len(queue) > 0:
cur_r, cur_c = queue.popleft()
for adjacent_index in adjacent_indices:
next_r = cur_r + adjacent_index[0]
next_c = cur_c + adjacent_index[1]
if 0 <= next_r < l and 0 <= next_c < l:
if board[next_r][next_c] == -1:
board[next_r][next_c] = board[cur_r][cur_c] + 1
if next_r == d_r and next_c == d_c:
return board[next_r][next_c]
queue.append((next_r, next_c))
print(answer)
t = int(input())
for _ in range(t):
answer = solve()
print(answer)
'코딩테스트 > Python' 카테고리의 다른 글
1335. Minimum Difficulty of a Job Schedule 풀이 python (1) | 2023.12.30 |
---|---|
codility의 PrettyTiling 문제를 보며 느낀점 (0) | 2023.02.08 |
백준 input = sys.stdin.readline 차이 (0) | 2021.07.02 |