poj 2243

BFS

#include <iostream>
#include <stdio.h>
#include <queue>
#include <vector>
#include <string.h>
#include <algorithm>
using namespace std;
struct node
{
    int x,y;
};
int dir[8][2]={-2,-1,-2,1,-1,-2,-1,2,1,-2,1,2,2,-1,2,1};
int move[10][10];
int ex,ey;
bool OK(node &b)
{
    if(b.x<1||b.x>8||b.y<1||b.y>8||move[b.x][b.y])
      return false;
    return true;
}
void BFS(int x,int y)
{
    node a,b;
    queue<node> Q;
    a.x=x;  a.y=y;
    Q.push(a);
    int i;
    while(!Q.empty())
    {
        a=Q.front();Q.pop();
        
        for(i=0;i<8;i++)
        {
            b.x=a.x+dir[i][0];
            b.y=a.y+dir[i][1];
            if(b.x==x&&b.y==y) continue;
            if(OK(b))
             {
                 move[b.x][b.y]=move[a.x][a.y]+1;
                 Q.push(b);
             }
            if(b.x==ex&&b.y==ey) return;
        }
    }

}
int main()
{
   char op1[5],op2[5];
   while(scanf("%s %s",op1,op2)!=EOF)
   {
       memset(move,0,sizeof(move));
       int x=op1[0]-'a'+1  ,   y=op1[1]-'0';
           ex=op2[0]-'a'+1; 
           ey=op2[1]-'0';
     //  printf("%d %d==
",ex,ey);
     
       if(x!=ex||y!=ey)
         BFS(x,y);
    printf("To get from %s to %s takes %d knight moves.
",op1,op2,move[ex][ey]);

   }
}
View Code
原文地址:https://www.cnblogs.com/2014acm/p/3898960.html