CSU-ACM2017暑期训练6-bfsH

来源:互联网 发布:强子纹身器材淘宝 编辑:程序博客网 时间:2024/05/16 11:46

ACM小组的Samsara和Staginner对中国象棋特别感兴趣,尤其对马(可能是因为这个棋子的走法比较多吧)的使用进行深入研究。今天他们又在 构思一个古怪的棋局:假如Samsara只有一个马了,而Staginner又只剩下一个将,两个棋子都在棋盘的一边,马不能出这一半棋盘的范围,另外这 一半棋盘的大小很奇特(n行m列)。Samsara想知道他的马最少需要跳几次才能吃掉Staginner的将(我们假定其不会移动)。当然这个光荣的任 务就落在了会编程的你的身上了。

Input
每组数据一行,分别为六个用空格分隔开的正整数n,m,x1,y1,x2,y2分别代表棋盘的大小n,m,以及将的坐标和马的坐标。(1<=x1,x2<=n<=20,1<=y1,y2<=m<=20,将和马的坐标不相同)

Output
输出对应也有若干行,请输出最少的移动步数,如果不能吃掉将则输出“-1”(不包括引号)。

Sample Input
8 8 5 1 4 5
Sample Output
3

写这一道题的题解是因为有一个地方即马如果撇脚是走不了的情况,考虑了一下,当它撇脚时如果有解,那么假设撇脚可走的话,和不走撇脚的路线,其步数是相同的。
上传了一个撇脚时假设能走与不走撇脚时的路线,可以看到这两种选择以后的路线步数是相同的(这里假定最优步数中,需要将马走到将的旁边一格)
这里写图片描述
这里写图片描述
给出代码:

#include <cstdio>#include <cstdlib>#include <cstring>#include <iostream>#include <vector>#include <string> #include <algorithm>#include <list>#include <set>#include <cmath>#include <queue> using namespace std;int cx[] = {-2,-2,-1,1,2,2,1,-1};//左上角,顺时针 int cy[] = {-1,1,2,2,1,-1,-2,-2};int visit[500];int main(){    int n,m,e_x,e_y,s_x,s_y;    queue<int> b;    while(scanf("%d%d%d%d%d%d",&n,&m,&e_x,&e_y,&s_x,&s_y) != EOF){        memset(visit,0,sizeof(visit));        int t = (s_x - 1) * m + (s_y - 1);        b.push(t);        visit[t] = 1;        while(!b.empty()){            t = b.front();            int x = t / m;            int y = t % m;            if(x == e_x - 1 && y == e_y - 1)                break;            b.pop();            for(int i = 0;i < 8;i++){                int x0 = x + cx[i];                int y0 = y + cy[i];                if(x0 < 0 || x0 >= n || y0 < 0 || y0 >= m)                    continue;                int t0 = x0 * m + y0;                if(!visit[t0])                    b.push(t0),visit[t0] = visit[t] + 1;            }        }        if(!b.empty()){            cout << visit[t] - 1 << endl;            while(!b.empty())                b.pop();        }        else{            cout << -1 << endl;        }    }    return 0;}
原创粉丝点击