简单题,一次BFS,注意队列的使用
#include<iostream>
#include<cstdio>
#include<cstring>
#include<memory>
#include<queue>
#include<algorithm>
#include<string>
using namespace std;
///
int steps;
int dir[8][2] = { {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1} };
queue<string> qu;
bool isOk(string temp)
{
if ( (temp[0] >= 'a') && (temp[0] <= 'h') && (temp[1] >= '1') && (temp[1] <= '8') )
return true;
else
return false;
}
void bfs(string startpos, string targetpos)
{
int i, j, cnt;
if (startpos == targetpos)
return;
string tmpStr, tmpTarget;
tmpStr = startpos;
tmpStr += '0';
qu.push(tmpStr);
while (!qu.empty())
{
tmpStr = qu.front();
qu.pop();
if (tmpStr[0] == targetpos[0] && tmpStr[1] == targetpos[1])
{
steps = tmpStr[2] - '0';
while (!qu.empty())
qu.pop();
return;
}
for (i = 0; i < 8; i++)
{
tmpTarget = tmpStr;
tmpTarget[0] = tmpStr[0] + dir[i][1];
tmpTarget[1] = tmpStr[1] + dir[i][0];
tmpTarget[2] += 1;
if (isOk(tmpTarget))
qu.push(tmpTarget);
}
}
}
int main()
{
///
int i, j;
string startpos, targetpos;
while ((cin >> startpos) && (cin >> targetpos))
{
steps = 0;
bfs(startpos, targetpos);
cout << "To get from " << startpos << " to " << targetpos << " takes " << steps << " knight moves." << endl;
}
///
return 0;
}