POJ2243(BFS)

      跳马问题,从一个位置跳到另一个位置最少需要几步?我用的BFS,94MS,不知道那些牛人的0MS是怎么做到的!说明我的代码还可以优化,希望路过的高手指点下啊!

     我的代码:

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;

struct pos
{
  int x,y,step;     
};
pos start,end;

bool board[8][8];//棋盘
int d[8][2]={{1,2},{-1,2},{2,1},{-2,1},{1,-2},{-1,-2},{2,-1},{-2,-1}};//马的八个方向
int bfs(pos s,pos e);

int main()
{
  char  a[3],b[3];

   while(cin>>a>>b)
   {
       start.x = a[0]-'a';//将输入转化为棋盘中的位置
       start.y = a[1]-'1';
       end.x = b[0]-'a';
       end.y = b[1]-'1';
       start.step = 0;//初始化步数为0
       memset(board,false,sizeof(board));//false表示没有走过
       
       cout<<"To get from "<<a<<" to "<<b<<" takes "<<bfs(start,end)<<" knight moves."<<endl;                   
   }
  return 0;
}

int bfs(pos s,pos e)
{
     queue<pos> que;
     pos p;
     int i,dx,dy;
     while(1)
     {
        if(s.x == e.x && s.y == e.y)
         return s.step;
        for(i = 0 ; i < 8 ; ++i)
        {
            dx = s.x + d[i][0];
            dy = s.y + d[i][1];  
            if(dx < 0 || dx >= 8 || dy < 0 || dy >= 8 )//越界判断 
             continue;
            if( !board[dx][dy])//可以走
            {
                  p.x = dx;
                  p.y = dy;
                  board[dx][dy] = true;//走过后标记
                  p.step = s.step + 1;
                  que.push(p);//结点入队列    
            } 
         }         
         s = que.front();//取队首元素,继续广搜
         que.pop();//并且出队列    
     }
}

原文地址:https://www.cnblogs.com/HpuAcmer/p/2258212.html