※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 15242번 문제인 Knight이다.
문제는 아래 링크를 확인하자.

https://www.acmicpc.net/problem/15242 

 

15242번: Knight

In Chess, the knight is the weirdest of all the pieces. To begin with, the piece is actually a horse without any human riding it. The second reason is its movement pattern. It can move 2 cells forward and one to the side. Below you can see all the possible

www.acmicpc.net

주어진 문제의 상황은 각 체스판의 칸을 노드로 생각하고, 나이트의 움직임으로 이동할 수 있는 칸의 쌍을 에지로 하는 그래프로 모델링할 수 있다.

 

위와 같은 모델링에서, 주어진 문제는 한 노드에서 다른 노드까지의 최단거리를 구하는 문제와 같게 된다. 이는 BFS를 통해 간단히 알아낼 수 있다.

 

아래는 제출한 소스코드이다.

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int sR, sC, eR, eC;
int dist[8][8];

int dr[8] = { 1,2,2,1,-1,-2,-2,-1 };
int dc[8] = { 2,1,-1,-2,-2,-1,1,2 };

void bfs() {
	queue<pair<int, int>> que;
	que.push(make_pair(sR, sC));
	dist[sR][sC] = 1;
	while (!que.empty()) {
		int r = que.front().first, c = que.front().second; que.pop();
		for (int i = 0; i < 8; i++) {
			int rr = r + dr[i], cc = c + dc[i];
			if (rr < 0 || rr > 7 || cc < 0 || cc > 7 || dist[rr][cc]) continue;
			dist[rr][cc] = dist[r][c] + 1;
			que.push(make_pair(rr, cc));
		}
	}
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	string s1, s2; cin >> s1 >> s2;
	sR = s1[0] - 'a', sC = s1[1] - '1', eR = s2[0] - 'a', eC = s2[1] - '1';
	
	bfs();

	cout << dist[eR][eC] - 1;
}
728x90

'BOJ' 카테고리의 다른 글

[BOJ 15235 // C++] Olympiad Pizza  (0) 2023.05.18
[BOJ 15237 // C++] Cipher  (0) 2023.05.17
[BOJ 15245 // C++] Boom!  (0) 2023.05.15
[BOJ 1911 // C++] 흙길 보수하기  (0) 2023.05.14
[BOJ 15244 // C++] Debug  (0) 2023.05.13

+ Recent posts