Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 다익스트라
- 누적합
- MST
- 다이나믹프로그래밍
- 수학
- 에라토스테네스의 체
- 플로이드-워셜
- 해시
- 투포인터
- 구현
- 브루트포스
- DFS
- 분할정복
- 재귀
- 시뮬레이션
- 그래프 이론
- 그래프 탐색
- GROUP BY
- join
- 그리디
- 다이나믹 프로그래밍
- 서브쿼리
- BFS
- 크루스칼
- 트리
- 백트래킹
- 자료구조
- 우선순위큐
- 다시
- DP
Archives
- Today
- Total
기록하고 까먹지 말기
7562 본문
날짜 : 2023. 02. 14
사용 언어 : python
문제
코드
import sys
from collections import deque
t = int(sys.stdin.readline()) # 테스트케이스
def bfs(r1, c1, r2, c2, r): # 시작, 도착, 변의 길이
q = deque()
cnt = 0 # 이동횟수
q.append([r1, c1, cnt])
dx = [-2, -1, 1, 2, 2, 1, -1, -2]
dy = [1, 2, 2, 1, -1, -2, -2, -1]
while q:
x, y, c = q.popleft()
for i in range(8):
x1 = x + dx[i]
y1 = y + dy[i]
if x1 in range(r) and y1 in range(r): # 범위에 포함
if x1 == r2 and y1 == c2: # 방문
print(c+1) # 이동횟수 출력
return
if not graph[x1][y1]:
graph[x1][y1] = True # 방문처리
q.append([x1, y1, c+1]) # 큐에 삽입
for _ in range(t):
l = int(sys.stdin.readline()) # 한 변의 길이
graph = [[False] * l for _ in range(l)]
r1, c1 = map(int, sys.stdin.readline().split()) # 시작
r2, c2 = map(int, sys.stdin.readline().split()) # 도착
if r1 == r2 and c1 == c2 :
print(0)
continue
bfs(r1, c1, r2, c2, l)
풀이
- 최소 탐색길이를 찾는 것이기 때문에 BFS를 활용해서 풀이하는 문제였다.
- 테스트케이스마다 기본 그래프를 초기화 한 후 풀도록 주의해야했다.
알게된 점
-
참고 사이트
-