题目链接
题目大意:
给起点和终点,求出最短路径长度。
分析:
是UVA1599题目的一半,只从终点开始BFS,用map记录每个点到终点的距离(不要忘记标记)。
map中起点键对应的值即为最短距离。
#include <bits/stdc++.h>
using namespace std;
string beg, ed;
int dir[10][10] = {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
map<string,int> vis;
map<string,int> dis;
int cnt;
bool feasible(char ch1, char ch2) {
return ch1 >= 'a' && ch1<='h' && ch2>='1' && ch2<='8';
}
void bfs_re() {
queue<string> queue1;
queue1.push(ed);
dis[ed] = 0;
vis[ed] = 1;
while(!queue1.empty()) {
string u = queue1.front(); queue1.pop();
for(int i = 0; i < 8; i++) {
char ch1 = (char)(u[0]+dir[i][0]);
char ch2 = (char)(u[1]+dir[i][1]);
if(feasible(ch1,ch2)) {
char vv[5];
vv[0] = ch1, vv[1] = ch2, vv[2] = 0;
string v = vv;
if(!vis.count(v)) {
vis[v] = 1;
dis[v] = dis[u] + 1;
queue1.push(v);
}
}
}
}
}
int main() {
freopen("i.txt","r",stdin);
freopen("o.txt","w",stdout);
while(cin >> beg >> ed) {
cnt = 0;
dis.clear(); vis.clear();
bfs_re();
cout << "To get from "<< beg <<" to " << ed << " takes " << dis[beg] << " knight moves." << endl;
}
}