Problem C
跳马
时限:1000ms 内存限制:10000K 总时限:3000ms
描述:
在国际象棋中,马的走法与中车象棋类似,即俗话说的“马走日”,下图所示即国际象棋中马(K)在一步能到达的格子(其中黑色的格子是能到达的位置)。
现有一200*200大小的国际象棋棋盘,棋盘中仅有一个马,给定马的当前位置(S)和目标位置(T),求出马最少需要多少跳才能从当前位置到达目标位置。
输入:
本题包含多个测例。输入数据的第一行有一个整数N(1<=N<=1000),表示测例的个数,接下来的每一行有四个以空格分隔的整数,分别表示马当前位置及目标位置的横、纵坐标C(x,y)和G(x,y)。坐标由1开始。
输出:
对于每个测例,在单独的一行内输出一个整数,即马从当前位置跳到目标位置最少的跳数。
输入样例:
2
1 1 2 1
1 5 5 1
输出样例:
3
4
#include <iostream>
#include <queue>
using namespace std;
queue <pair<int, int> > q;
char s[201][201];
int d[201][201];
int start_x, start_y, end_x, end_y;
int n;
int dx[8] = {1, 1, 2, 2, -1, -1, -2, -2};//八个方向
int dy[8] = {2, -2, 1, -1, 2, -2, 1, -1};
bool can(int x, int y) {
if (x < 1 || y < 1 || y > 200 || x > 200) {
return false;
}
return true;
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> start_x >> start_y >> end_x >> end_y;
memset(d, -1, sizeof(d));
d[start_x][start_y] = 0;
pair<int, int> temp(start_x, start_y);
q.push(temp);
while (q.size()) {
pair<int, int> now = q.front();
q.pop();
for (int i = 0; i < 8; i++) {
pair<int, int> next(now.first + dx[i], now.second + dy[i]);
if (!can(next.first, next.second)) {
continue;
}
if (d[next.first][next.second] == -1) {
d[next.first][next.second] = d[now.first][now.second] + 1;
q.push(next);
}
}
}
cout << d[end_x][end_y] << endl;
}
return 0;
}