UVA-439, Knight Moves(深度优先搜索)
#include<iostream>
#include<queue>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
struct Point
{
int x_, y_;
int route;
};
int dic[8][2] = {-1,2 ,1,2 ,2,1 ,2,-1 ,1,-2 ,-1,-2 ,-2,-1 ,-2,1};
int vis[10][10]; /*判断是否访问过*/
string fir, sec;
int ans; /*记录最短路*/
int x1, y1, x2, y2;
void dfs()
{
if(x1 == x2 && y1 == y2)
{
ans = 0;
return ;
}
Point p;
p.x_ = x1;
p.y_ = y1;
vis[x1][y1] = 1;
p.route = 0;
queue<Point> rr;
rr.push(p);
while(!rr.empty())
{
// if(x1 == x2 && y1 == y2)
// break;
Point q;
for(int i = 0; i < 8; i++)
{
q.x_ = rr.front().x_ + dic[i][0];
q.y_ = rr.front().y_ + dic[i][1];
q.route = rr.front().route + 1;
if(vis[q.x_][q.y_] == 1 || q.x_ < 0 || q.y_ < 0 || q.x_ > 7 || q.y_ > 7)
continue;
else
{
vis[q.x_][q.y_] = 1;
rr.push(q);
if(q.x_ == x2 && q.y_ == y2)
{
ans = q.route;
break; /*找到了*/
}
}
}
if(q.x_ == x2 && q.y_ == y2)
break;
rr.pop();
}
}
int main()
{
while(cin >> fir >> sec)
{
memset(vis, 0, sizeof(vis));
x1 = (int)fir[0] - 'a';
y1 = (int)fir[1] - '0' - 1;
x2 = (int)sec[0] - 'a';
y2 = (int)sec[1] - '0' - 1;
dfs();
cout << "To get from " << fir << " to " << sec << " takes " << ans << " knight moves." << endl;
}
}