Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <algorithm>
- using namespace std;
- struct position { //заведем структуру из пар для хранения координат
- int x;
- int y;
- };
- position makepair (int x, int y) {
- position pair;
- pair.x = x;
- pair.y = y;
- return pair;
- }
- vector <position> variants (position location) {
- //найдем координаты клеток, в которую может попасть конь из текущей (8 вариантов)
- //(x+2)(y-1) (x+2)(y+1) (x-2)(y-1) (x-2)(y+1) (x+1)(y+2) (x-1)(y+2) (x+1)(y-2) (x+1)(y-2)
- //для перебора данных вариантов создадим два вектора
- vector <int> change_x = {2, 2, 1, 1, -1, -1, -2, -2};
- vector <int> change_y = {1, -1, 2, -2, 2, -2, 1, -1};
- vector <position> newx(8);
- for (int i = 0; i < 8; i++) {
- newx[i].x = location.x + change_x[i];
- newx[i].y = location.y + change_y[i];
- }
- return newx;
- }
- bool check (position g, int size) { //проверка на попадание в рамки доски
- if (g.x > size || g.x < 1 || g.y > size || g.y < 1) return false;
- else return true;
- }
- int main() {
- int N = 8;
- int x1, y1, x2, y2;
- char x_1, x_2;
- cin >> x_1 >> y1 >> x_2 >> y2;
- x1 = x_1 - 96;
- x2 = x_2 - 96;
- if (x1 == x2 && y1 == y2) {
- cout << 0;
- return(0);
- }
- //не забыть проверять на попадание в рамки доски
- position g = makepair(x1, y1);
- queue <position> fire;
- vector <vector <int>> used (N, vector <int> (N));
- vector <position> news;
- vector <vector <position>> parent (N, vector <position> (N, {123, 123}));
- fire.push(g);
- parent[g.x-1][g.y-1] = {-1, -1};
- used[x1-1][y1-1] = 1;
- while (!fire.empty()) {
- position temp = fire.front();
- fire.pop();
- news = variants(temp);
- for (int i = 0; i < 8; i++) {
- if (check(news[i], N) == true && used[news[i].x-1][news[i].y-1] == 0) {
- used[news[i].x-1][news[i].y-1] = 1;
- fire.push(news[i]);
- parent[news[i].x-1][news[i].y-1] = temp;
- if (news[i].x == x2 && news[i].y == y2) goto lengthcount;
- }
- }
- }
- if (parent[x2-1][y2-1].x == 123 && parent[x2-1][y2-1].y == 123) {
- cout << "-1";
- return(0);
- }
- lengthcount:
- int length = 0;
- vector <position> path;
- for (position t = makepair(x2, y2); t.x != -1 && t.y != -1; t = parent[t.x - 1][t.y - 1]) {
- length++;
- }
- if ((length - 1) % 2 == 0) cout << length / 2;
- else cout << "-1";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement