杭电1372 典型的广度优先算法

本文介绍了一种基于深度优先搜索的算法,用于查找棋盘上骑士从一个位置到另一个位置所需的最少步数。

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

 

 

#include<iostream>
#include<string>
using namespace std;
#define M 200
#define N 10
using namespace std;
struct node
{
 int col;//行
 int row;//列
 int pre;//上一个节点
}sq[M];
int map[N][N]={0};
string str1,str2;
int si,sj,ei,ej;
int dir[8][2]={{2,1},{2,-1},{-2,1},{-2,-1},{1,-2},{1,2},{-1,2},{-1,-2}}; //马每次可能跳的方向
//int map[10][10]
int count_step(node sq[],int rear)//输出路径
{
 int i,count=0;
 i=rear;
 //do
 while(i!=0)
 {
  i=sq[i].pre;
  count++;
 }
 return count;
}
//int map[n2][m2]
void short_way()
{
 int i,j,k,front=1,rear=1,x,y;
 memset(map,0,sizeof(map)); //初始化

 //初始化入口点
 sq[front].col=si;//入口点横坐标
 sq[front].row=sj;//纵坐标
 sq[front].pre=0;//入口点在sq[]中前驱结点为sq[0]
 map[si][sj]=-1;//标记入口点已经到达过
 if(si==ei&&sj==ej)//起点==终点
 {
  cout<<"To get from "<<str1<<" to "<<str2<<" "<<"takes "<<0<<" knight moves."<<endl;
   return;
 }
 while(front<=rear)
 {
  x=sq[front].col;
  y=sq[front].row;
  for(k=0;k<8;k++)
  {
   i=x+dir[k][0];
   j=y+dir[k][1];
   if(map[i][j]==0&&i>=0&&i<8&&j>=0&&j<8)//符合条件的点入队
   {
    rear++;
    sq[rear].col=i;
    sq[rear].row=j;
    sq[rear].pre=front;
    map[i][j]=-1;
   }
   if(i==ei&&j==ej)//找到了
   {
   // for(int m=0;m<rear;m++) cout<<sq[m].pre<<" ";cout<<endl;
    int flag=count_step(sq,rear);
    cout<<"To get from "<<str1<<" to "<<str2<<" "<<"takes "<<flag-1<<" knight moves."<<endl;
    return;
   }
  }
  front++;
 }
 //return 0;//没有路径
}
int main()
{
 //freopen("1.txt","r",stdin);
 while(cin>>str1>>str2)
 {
  si = str1[0]-97; //列从0开始,将字符转化为整数,a的ASCII码97
  sj = str1[1]-'1';//行也从0开始,将字符整数转化为整数
  ei = str2[0]-97;
  ej = str2[1]-'1';
  short_way();
 }
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值