1015 Knight Moves

来源:互联网 发布:iphone怎么授权软件 编辑:程序博客网 时间:2024/05/16 07:39

1015 Knight Moves

     题意:国际象棋棋盘,给定起始点和重点,求最少移动次数。

思路:在国际象棋棋盘上,共有八个方向的移动位置,对每个移动方向,将其保存到队列中,因为队列逐层搜索,所以必定可以找到最短的路径。

感想:输入有些困难,要将字符和数字分开,通过getchar()读取字符这点比较重要。

#include<iostream>

#include<queue>

#include<stdio.h>

#include<string.h>

using namespace std;

struct node{

   int x,y,cnt;

};

node s,e;

int a[9][9];

intdri[8][2]={{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};

int bfs(){

   memset(a,0,sizeof(a));

   node p,q;

   s.cnt=0;

    queue<node>b;

   b.push(s);

   a[s.x][s.y]=1;

   while(!b.empty()){

       p=b.front();

       b.pop();

       if(p.x==e.x&&p.y==e.y)

           return p.cnt;

       for(int i=0;i<8;i++){

           q.x=p.x+dri[i][0];

           q.y=p.y+dri[i][1];

           if(q.x<1||q.x>8||q.y<1||q.y>8) continue;

           if(a[q.x][q.y]==1) continue;

           q.cnt=p.cnt+1;

           a[q.x][q.y]=1;

           b.push(q);

       }

    }

   return -1;

}

int main(){

   char row,w;

   int col,l;

   int min;

   while(scanf("%c",&row)!=EOF){

       scanf("%d",&col);

       getchar();

       scanf("%c%d",&w,&l);

       getchar();

       s.x=row-'a'+1;

       s.y=col;

       e.x=w-'a'+1;

       e.y=l;

       if(s.x==e.x&&s.y==e.y)

           min=0;

       else

           min=bfs();

       cout<<"To get from "<<row<<col<<"to "<<w<<l<<" takes "<<min<<"knight moves."<<endl;

    }

   return 0;

}

0 0
原创粉丝点击