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 |
Tags
- 트리
- 역방향 반복자
- 스프링
- 다이나믹프로그래밍
- CI/CD
- 브루트포스
- 백준
- 도커
- 이분탐색
- GIT
- 분할정복
- 그래프
- 자료구조
- BFS
- 그리드
- 그리드 알고리즘
- AWS
- Spring
- 다이나믹 프로그래밍
- SQL
- github action
- 알고리즘
- 순열
- 자바
- 컴퓨터 네트워크
- TCP
- HTTP
- 재귀
- dfs
- 분할 정복
Archives
- Today
- Total
코딩성장스토리
백준:7562번 나이트의 이동 본문
https://www.acmicpc.net/problem/7562
7562번: 나이트의 이동
체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수
www.acmicpc.net
BFS로 풀면 그게 곧 최소 거리이므로 목적지 도달할 떄 탈출하면 된다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int, int> pii;
int arr[301][301];
bool check[301][301];
int dx[] = { 1,2,-1,-2,1,2,-1,-2 };
int dy[] = { 2,1,2,1,-2,-1,-2,-1 };
int t, l, startx,starty,endx,endy;
void reset(int l) {
for (int i = 0; i < l; i++) {
for (int k = 0; k < l; k++) {
arr[i][k] = 0;
check[i][k] = false;
}
}
}
int bfs(int x, int y) {
queue<pii> p;
p.push(pii(x, y));
while (!p.empty()) {
x = p.front().first;
y = p.front().second;
int before = arr[y][x];
if (x == endx && y == endy) {
return arr[endy][endx];
}
p.pop();
for (int i = 0; i < 8; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < l && ny >= 0 && ny < l) {
if (!check[ny][nx]) {
p.push(pii(nx, ny));
check[ny][nx] = true;
arr[ny][nx] = before + 1;
}
}
}
}
}
int main()
{
cin >> t;
while (t--) {
cin >> l;
cin >> startx >> starty;
cin >> endx >> endy;
bfs(startx, starty);
cout << arr[endy][endx] << '\n';
reset(l);
}
}
'백준 코딩' 카테고리의 다른 글
백준 1904번 : 01타일 (0) | 2022.06.02 |
---|---|
백준 13305번: 주유소 (0) | 2022.04.25 |
백준 2583번 : 영역 구하기 (0) | 2022.03.18 |
백준 1697번:숨바꼭질 (0) | 2022.02.07 |
백준 1182번: 부분수열의 합 (0) | 2022.02.06 |