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
| #include <bits/stdc++.h>
using namespace std; pair<int,int> at(string s) { return {'8' - s[1], s[0] - 'a'}; } int knight(std::string start, std::string finish) { if(start == finish) return 0; queue<pair<int,int>> q; vector<vector<int>> vis(8,vector<int>(8,INT_MAX)); auto push = [&](int y, int x, int c) { if(vis[y][x] > c) { vis[y][x] = c; q.push({y,x}); } }; push(at(start).first, at(start).second, 0); int dy[8]{-1,-2,-2,-1,1,2,2,1}, dx[8]{-2,-1,1,2,2,1,-1,-2}; while(q.size()) { auto [y,x] = q.front(); q.pop(); for(int i = 0; i < 8; i++) { int ny = y + dy[i], nx = x + dx[i]; if(0 <= ny and ny < 8 and 0 <= nx and nx < 8) { push(ny,nx,vis[y][x] + 1); auto [gy,gx] = at(finish); if(gy == ny and gx == nx) return vis[ny][nx]; } } } return -1; }
|