ZOJ1091 Knight Moves
一个经典BFS题,详细分析待后
#include <iostream>
#include <string>
#include <queue>
using namespace std;
int WAY[8][2]={{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{-1,2},{-1,-2},{1,-2}};
bool FLAG[8][8];
struct NODE
{
int x;
int y;
int step;
};
int main()
{
string a,b;
int tx,ty,i,j;
queue<NODE> KnightQueue;
NODE StartNode,EndNode,Temp,TT;
while(cin >> a >> b)
{
for(i=0;i<8;++i)
for(j=0;j<8;++j)
FLAG[i][j] = false;
StartNode.x = a[0] - 'a';
StartNode.y = a[1] - '1';
StartNode.step = 0;
//cout << StartNode.x << endl << StartNode.y << endl;
EndNode.x = b[0] - 'a';
EndNode.y = b[1] - '1';
//begin
KnightQueue.push(StartNode);
FLAG[StartNode.x][StartNode.y] = true;
while(!KnightQueue.empty())
{
Temp = KnightQueue.front();
KnightQueue.pop();
if(Temp.x==EndNode.x&&Temp.y==EndNode.y)
break;
for(i=0;i<8;++i)
{
tx = Temp.x + WAY[i][0];
ty = Temp.y + WAY[i][1];
if(tx>=0&&tx<8&&ty>=0&&ty<8&&FLAG[tx][ty]==false)
{
TT.x = tx;
TT.y = ty;
TT.step = Temp.step + 1;
KnightQueue.push(TT);
FLAG[tx][ty] = true;
}
}
}
cout << "To get from " << a << " to " << b << " takes " << Temp.step << " knight moves." << endl;
while(!KnightQueue.empty())
KnightQueue.pop();
}
return 0;
}
浙公网安备 33010602011771号