H-Diamond CSU-1224: Crazy Chess Search for ACM Team

H - Diamond CSU - 1224 

The ACM team, Samsara and Stackinner, are particularly interested in Chinese chess, especially in the use of horses (probably because they walk more often). Today they are conceiving an odd chess game: if Samsara has only one horse and Staginner has only one general, two pieces are on one side of the chessboard, the horse can't reach half of the chessboard, and the other half of the chessboard is of a strange size (n rows and m rows). Samsara wants to know that his horse needs to jump at least a few times to eat Staginner's generals (we assume it won't move). Of course, this glorious task falls on you who can program.

Input

Each group of data is divided into six positive integers n,m,x1,y1,x2,y2 separated by spaces, representing the size of the chessboard n,m, coordinates of the horse and the coordinates of the chessboard. (1 < = x1, x2 < = n < = 20, 1 < = y1, Y2 < = m < = 20, which will be different from the coordinates of horses)

Output

The output corresponds to several lines. Please output the least number of moving steps. If you can't eat them, you will output "- 1" (excluding quotation marks).

Sample Input

8 8 5 1 4 5

Sample Output

3

Hint

 

Search template questions

 

#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <math.h>

typedef long long LL;
typedef long double LD;
using namespace std;
const int  maxn=22;
char ma[maxn][maxn];
int vis[maxn][maxn];
//int f[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
//int f[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int f[8][2]={{-2,-1},{-2,1},{2,-1},{2,1},{-1,-2},{1,-2},{-1,2},{1,2}};
int N,M,T;
struct node
{
    int x,y;
    int step;
    friend bool operator <(node a,node b)
    {
        return a.step>b.step;
    }
};
priority_queue<node>q;
bool OK(int x,int y)
{
    if(x>0&&y>0&&x<=N&&y<=M)
        return true;
    return false;
}
void bfs(node st,node en)
{
    q.push(st);
    vis[st.x][st.y]=0;
    while(!q.empty())
    {
        node t=q.top();
        q.pop();
        //printf("*****%d %d %d\n",t.x,t.y,t.step);
        if(t.x==en.x&&t.y==en.y)
        {
            printf("%d\n",t.step);
            return;
        }
        for(int i=0;i<8;i++)
        {
            int xx=t.x+f[i][0];
            int yy=t.y+f[i][1];
            if(OK(xx,yy)&&(vis[xx][yy]>t.step+1||vis[xx][yy]==-1))
            {
               // printf("%d %d %d\n",xx,yy,t.step+1);
                q.push((node){xx,yy,t.step+1});
                vis[xx][yy]=t.step+1;
            }
        }
    }
    printf("-1\n");
}
int main()
{
    node st,en;
    while(~scanf("%d%d%d%d%d%d",&N,&M,&en.x,&en.y,&st.x,&st.y))
    {
        memset(vis,-1,sizeof(vis));
        while(!q.empty())q.pop();
        st.step=0;
        bfs(st,en);
    }
    return 0;
}

 

Posted by scriptkiddie on Mon, 04 Feb 2019 09:36:16 -0800