joj2410: The knight problem

来源:互联网 发布:大数据与精准扶贫 编辑:程序博客网 时间:2024/05/16 09:20
#include<iostream>#include<cstdio>#include<queue>using namespace std;typedef struct Point{    int x, y;}POINT;queue <POINT> me;POINT Begin , End;bool visited[9][9];bool flag;int ans;int movei[8]= {2,-2,1,-1,2,-2,1,-1};int movej[8]= {1,-1,2,-2,-1,1,-2,2};void init(){    int i, j;    for(i = 0; i < 9; i++)        for(j = 0; j < 9; j++)            visited[i][j] = false;}bool isok(POINT *p){    if(p->x == End.x && p->y == End.y)        return true;    else        return false;}bool isin(POINT *pt){    if(pt->x >= 1 && pt->x <= 8)        if(pt->y >= 1 && pt->y <= 8)            return true;    return false;}void change(char *str, POINT *pt){    pt->x = str[0] - 'a' +1;    pt->y =str[1] - '0';}void bfs(){    int i, q, casenum;    POINT pt, tp;    casenum = 1;    while(!me.empty())    {        ans++;        q = 0;        while(casenum--)        {            pt = me.front();            me.pop();            for( i = 0; i < 8; i++)            {                tp.x = pt.x + movei[i];                tp.y = pt.y + movej[i];                if(isin(&tp))                {                    if(visited[tp.x][tp.y])                        continue;                    else                    {                        if(isok(&tp))                        {                            flag = true;                            return;                        }                        else                        {                            visited[tp.x][tp.y] = true;                            me.push(tp);                            q++;                        }                    }                }            }        }        casenum = q;    }    if(me.empty())        flag = false;    return ;}int main(){    int n, i, casenum;    POINT tp;    char str[10];    casenum = 1;    while(true)    {        while(!me.empty())        me.pop();        flag = true;        ans = 0;        init();        scanf("%d", &n);        if(-1 == n)            break;        for(i = 0; i < n; i++)        {            scanf("%s", str);            change(str, &tp);            visited[tp.x][tp.y] = true;        }        scanf("%s", str);        change(str, &Begin);        scanf("%s", str);        change(str, &End);        me.push(Begin);        visited[Begin.x][Begin.y] = true;        if(isok(&Begin))            printf("Board %d: %d moves\n", casenum, ans);        bfs();        if(flag)            printf("Board %d: %d moves\n", casenum, ans);        else            printf("Board %d: not reachable\n", casenum);        casenum++;    }    return 0;}
题目链接