这道题是标准的骑士问题,但是当时没有考虑其实和终止位置相同的情况,所以就浪费了好多时间。好在最后想出来了。
题目:
AC代码:
#include <iostream>
#include <queue>
using namespace std;
void jump();
int board[12][12];
int xend;
int yend;
class point
{
public:
int x;
int y;
int number;
};
queue<point> q1;
void init()
{
for(int i = 2; i < 10; i++)
for(int j = 2; j < 10; j++)
board[i][j] = 0;
for(int i = 0; i < 12; i++)
{
board[i][0] = -1;
board[i][1] = -1;
board[i][10] = -1;
board[i][11] = -1;
}
for(int i = 2; i < 10; i++)
{
board[0][i] = -1;
board[1][i] = -1;
board[10][i] = -1;
board[11][i] = -1;
}
}
int main()
{
int b;
int k = 1;
init();
int beg1, beg2, end1, end2;
cin >> beg1>> beg2;
cin >> end1 >> end2;
xend = end1+ 1;
yend = end2+ 1;
if (beg1 == end1 && beg2 == end2) {
cout << 0 << endl;
return 0;
}
point p1;
p1.x = beg1+1;
p1.y = beg2+1;
p1.number = 0;
q1.push(p1);
jump();
if(board[xend][yend] == 0)
{
cout << "not reachable" << endl;
}
else
{
cout << board[xend][yend] << endl;
}
return 0;
}
void jump()
{
while(!q1.empty())
{
point p0 = q1.front();
q1.pop();
point p1;
p1.x = p0.x-1;
p1.y = p0.y-2;
p1.number = p0.number + 1;
if(board[p1.x][p1.y] == 0)
{
board[p1.x][p1.y] = p1.number;
q1.push(p1);
}
p1.x = p0.x-1;
p1.y = p0.y+2;
if(board[p1.x][p1.y] == 0)
{
board[p1.x][p1.y] = p1.number;
q1.push(p1);
}
p1.x = p0.x+1;
p1.y = p0.y-2;
if(board[p1.x][p1.y] == 0)
{
board[p1.x][p1.y] = p1.number;
q1.push(p1);
}
p1.x = p0.x+1;
p1.y = p0.y+2;
if(board[p1.x][p1.y] == 0)
{
board[p1.x][p1.y] = p1.number;
q1.push(p1);
}
p1.x = p0.x-2;
p1.y = p0.y-1;
if(board[p1.x][p1.y] == 0)
{
board[p1.x][p1.y] = p1.number;
q1.push(p1);
}
p1.x = p0.x-2;
p1.y = p0.y+1;
if(board[p1.x][p1.y] == 0)
{
board[p1.x][p1.y] = p1.number;
q1.push(p1);
}
p1.x = p0.x+2;
p1.y = p0.y-1;
if(board[p1.x][p1.y] == 0)
{
board[p1.x][p1.y] = p1.number;
q1.push(p1);
}
p1.x = p0.x+2;
p1.y = p0.y+1;
if(board[p1.x][p1.y] == 0)
{
board[p1.x][p1.y] = p1.number;
q1.push(p1);
}
}
}