POJ2243 题目理解

题目链接:http://poj.org/problem?id=2243 POJ2243 dfs or bfs

#include
#include
#include
#include
#include
#include
using namespace std;

int cnt;
bool vis[9][9];
char s1[5], s2[5];
int  ex, ey, to[8][2]={-2,1, -1,2, 1,2, 2,1, 2,-1, 1,-2, -1,-2, -2,-1 };
struct node{
    int x,y,cnt;
};
int check(int x,int y)
{
    if(x<0 || y<0 || x>=8 || y>=8 || vis[x][y])
        return 1;
    return 0;
}
void bfs(){
    queue Q;
    node q, next, p;
    p.x=s1[0]-'a';
    p.y=s1[1]-'1';
    p.cnt=0;
    ex=s2[0]-'a';
    ey=s2[1]-'1';
    cnt=0;
    memset(vis, 0, sizeof(vis));
    vis[p.x][p.y]=true;
    Q.push(p);
    while(!Q.empty()){
        q=Q.front();
        Q.pop();
        if(q.x==ex&&q.y==ey)
        { cnt=q.cnt; return;}
        for(int i=0; i<8; i++){
            next.x=q.x+to[i][0];
            next.y=q.y+to[i][1];
            if(next.x == ex && next.y == ey)
            {  cnt=q.cnt+1; next.cnt =cnt; return;}
            if(check(next.x,next.y))
                continue;
            next.cnt = q.cnt+1;
            vis[next.x][next.y] = true;
            Q.push(next);
        }
    }
}

int main(){
    while(scanf("%s%s", &s1, &s2)==2){
        bfs();
    printf("To get from %s to %s takes %d knight moves.\n", s1, s2, cnt);
    }
    return 0;
}

刚开始题目理解的不清楚,就基本没有解出来的希望。。。。

你可能感兴趣的:(C++,搜索)