poj 2243 Knight Moves

本文介绍了一个使用广度优先搜索(BFS)算法解决国际象棋中骑士从一个位置到另一个位置所需最少移动次数的问题。通过遍历所有可能的骑士移动路径并记录步数,最终确定了从起点到终点的最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个8行8列的棋谱,任意给出knight的两个位子,问按照knight的走法,从其中的一个位子出发,问至少需要经过几步到达另外一个位子。 行用1-8表示,列用a-h表示,起始位置入队列,然后在当前结点能访问的结点依次搜索。。在进入队列前判断是否到达结束位置,用二维数组存储步数、、、、点击打开链接
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<vector> 
using namespace std;
typedef struct {
      int x;
      int y;
    }point;
vector<point> v;
int step[8][8];
point p;
bool ok;  //不知道为什么就是不让用find  
int index;  
int start_x, start_y, end_x, end_y;
int bfs(int x, int y, int time)  // time 每次记录当前的步数 
{
    if(x==end_x && y==end_y)
    {
      ok = true;
      return 0;
    }
    
    if(x-2>=0&&y-1>=0&&step[x-2][y-1]==-1)  //依次搜索 
    {
      step[x-2][y-1] = time+1;
      p.x = x-2;
      p.y = y-1;
      v.push_back(p);
    }
    
    if(x-1>=0&&y-2>=0&&step[x-1][y-2]==-1)
    {
      step[x-1][y-2] = time+1;
      p.x = x-1;
      p.y = y-2;
      v.push_back(p);
    }
    
    if(x-2>=0&&y+1<8&&step[x-2][y+1]==-1)
    {
      step[x-2][y+1] = time+1;
      p.x = x-2;
      p.y = y+1;
      v.push_back(p);
    }
    
    if(x-1>=0&&y+2<8&&step[x-1][y+2]==-1)
    {
      step[x-1][y+2] = time+1;
      p.x = x-1;
      p.y = y+2;
      v.push_back(p);
    }
    
    if(x+1<8&&y+2<8&&step[x+1][y+2]==-1)
    {
      step[x+1][y+2] = time+1;
      p.x = x+1;
      p.y = y+2;
      v.push_back(p);
    }
     
    if(x+2<8&&y+1<8&&step[x+2][y+1]==-1)
    {
      step[x+2][y+1] = time+1;
      p.x = x+2;
      p.y = y+1;
      v.push_back(p);
    }
    
    if(x+2<8&&y-1>=0&&step[x+2][y-1]==-1)
    {
      step[x+2][y-1] = time+1;
      p.x = x+2;
      p.y = y-1;
      v.push_back(p);
    }
    
    if(x+1<8&&y-2>=0&&step[x+1][y-2]==-1)
    {
      step[x+1][y-2] = time+1;
      p.x = x+1;
      p.y = y-2;
      v.push_back(p);
    }
}
int main()
{
    char s, e;
    int _s, _e;
    while(cin>>s>>_s>>e>>_e)
    {
    memset(step, -1, sizeof(step));
    start_x = (int)(s-'a'); 
    start_y = _s-1;
    end_x = (int)(e-'a');
    end_y = _e-1;
    p.x = start_x;
    p.y = start_y;
    v.clear(); 
    step[p.x][p.y]=0;
    v.push_back(p);
    ok = false;
    index = 0;
    while(!ok)
    {
      bfs(v[index].x, v[index].y, step[v[index].x][v[index].y]);   
      index++;
    }                       
    cout<<"To get from "<<s<<_s<<" to "<<e<<_e<<" takes "<<step[end_x][end_y]<<" knight moves."<<endl;
    }
   system("pause");
   return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值