开始时看不明题目,后来才知道原来说的是国际象棋中的骑士,其走法与中国象棋中的马相似,但没有绊马脚这一说法。那么从起点到终点,可以运用宽搜来解决。
Run Time: 0.05sec
Run Memory: 312KB
Code length: 3045Bytes
SubmitTime: 2011-12-24 20:17:55
// Problem#: 1936
// Submission#: 1123094
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <iostream>
#include <queue>
#include <string>
#include <cstring>
using namespace std;
struct Coor {
int x;
int y;
Coor( int i, int j ) { x = i; y = j; }
};
int main()
{
int T;
int count, step;;
string start, end;
int sx, sy, ex, ey;
bool visited[ 8 ][ 8 ];
cin >> T;
while ( T-- ) {
cin >> start >> end;
sx = start[ 1 ] - '1';
sy = start[ 0 ] - 'a';
ex = end[ 1 ] - '1';
ey = end[ 0 ] - 'a';
memset( visited, false, sizeof( visited ) );
queue<Coor> q;
Coor temp( sx, sy );
q.push( temp );
visited[ sx ][ sy ] = true;
step = 0;
while ( !visited[ ex ][ ey ] ) {
count = q.size();
step++;
while ( !visited[ ex ][ ey ] && count-- ) {
temp = q.front();
if ( temp.x - 2 >= 0 && temp.y - 1 >= 0 && !visited[ temp.x - 2 ][ temp.y - 1 ] ) {
q.push( Coor( temp.x - 2, temp.y - 1 ) );
visited[ temp.x - 2 ][ temp.y - 1 ] = true;
}
if ( temp.x - 2 >= 0 && temp.y + 1 < 8 && !visited[ temp.x - 2 ][ temp.y + 1 ] ) {
q.push( Coor( temp.x - 2, temp.y + 1 ) );
visited[ temp.x - 2 ][ temp.y + 1 ] = true;
}
if ( temp.x - 1 >= 0 && temp.y - 2 >= 0 && !visited[ temp.x - 1 ][ temp.y - 2 ] ) {
q.push( Coor( temp.x - 1, temp.y - 2 ) );
visited[ temp.x - 1 ][ temp.y - 2 ] = true;
}
if ( temp.x - 1 >= 0 && temp.y + 2 < 8 && !visited[ temp.x - 1 ][ temp.y + 2 ] ) {
q.push( Coor( temp.x - 1, temp.y + 2 ) );
visited[ temp.x - 1 ][ temp.y + 2 ] = true;
}
if ( temp.x + 1 < 8 && temp.y - 2 >= 0 && !visited[ temp.x + 1 ][ temp.y - 2 ] ) {
q.push( Coor( temp.x + 1, temp.y - 2 ) );
visited[ temp.x + 1 ][ temp.y - 2 ] = true;
}
if ( temp.x + 1 < 8 && temp.y + 2 < 8 && !visited[ temp.x + 1 ][ temp.y + 2 ] ) {
q.push( Coor( temp.x + 1, temp.y + 2 ) );
visited[ temp.x + 1 ][ temp.y + 2 ] = true;
}
if ( temp.x + 2 < 8 && temp.y - 1 >= 0 && !visited[ temp.x + 2 ][ temp.y - 1 ] ) {
q.push( Coor( temp.x + 2, temp.y - 1 ) );
visited[ temp.x + 2 ][ temp.y - 1 ] = true;
}
if ( temp.x + 2 < 8 && temp.y + 1 < 8 && !visited[ temp.x + 2 ][ temp.y + 1 ] ) {
q.push( Coor( temp.x + 2, temp.y + 1 ) );
visited[ temp.x + 2 ][ temp.y + 1 ] = true;
}
q.pop();
}
}
cout << "To get from " << start << " to " << end << " takes " << step << " knight moves.\n";
}
return 0;
}
本文探讨了国际象棋中骑士的走法及其与马的相似性,并通过实例展示了如何利用宽度优先搜索(宽搜)算法解决从起点到终点的问题。
829

被折叠的 条评论
为什么被折叠?



