跳马

来源:互联网 发布:安全课 防火知多少 编辑:程序博客网 时间:2024/05/01 04:47

跳马

时限: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 <cstring>#include <queue>using namespace std;int sx, sy;int fx, fy;int maze[201][201];int visited[201][201];int dir[8][2]={{-2,-1},{-1,-2},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}};struct Node{    int x;    int y;    Node(int x = 0, int y = 0):x(x), y(y){};};int bfs(){    queue<Node> q;    Node s = Node(sx, sy);    q.push(s);    visited[sx][sy] = 0;    while(!q.empty())    {        s = q.front();        q.pop();        int step = visited[s.x][s.y]+1;        for(int i = 0; i < 8; i++)        {            int nx = s.x+dir[i][0];            int ny = s.y+dir[i][1];            if(!visited[nx][ny] && nx > 0 && nx < 201 && ny > 0 && ny <201)            {                if(nx == fx && ny == fy)                    return step;                q.push(Node(nx, ny));                visited[nx][ny] = step;            }        }    }}int main(){    int t;    cin >> t;    while(t--)    {        memset(maze, 0, sizeof(maze));        memset(visited, 0, sizeof(visited));        cin >> sx >> sy;        cin >> fx >> fy;        cout << bfs() << endl;    }    return 0;}


0 0
原创粉丝点击