CF3A 【Shortest path of the king】

时间:2023-03-10 02:01:34
CF3A 【Shortest path of the king】

一句话题意:
在8 * 8的棋盘上,输出用最少步数从起点走到终点的方案

数据很小,可以广搜无脑解决

定义数据结构体

struct pos{
int x,y,s; //x、y表示横纵坐标,s表示步数
string move[]; //存储每一步的方案
};

移动时新旧状态传递

pos u=q.front();
q.pop();
for(int i=;i<;i++)
{
pos th;
th.x=u.x+dx[i];
th.y=u.y+dy[i];
th.s=u.s+;
for(int i=;i<=u.s;i++)
th.move[i]=u.move[i];
th.move[th.s]=st[i];
}

判断是否可以拓展

if(th.x<||th.x>||th.y<||th.y>||vis[th.x][th.y])
//越界或已访问
continue;

打标记,入队

vis[th.x][th.y]=;    //标记为已访问
q.push(th);

完整代码

#include<iostream>
#include<queue>
using namespace std;
struct pos{
int x,y,s;
string move[];
};
queue<pos>q;
int dx[]={-,,,,-,-,,};
int dy[]={,,,-,,-,,-};
string st[]={"L","R","U","D","LU","LD","RU","RD"};
bool vis[][];
int x,y;
int main()
{
string s1,s2;
cin>>s1>>s2;
q.push((pos){s1[]-'a'+,s1[]-'',,""});
vis[s1[]-'a'+][s1[]-'']=;
x=s2[]-'a'+,y=s2[]-'';
if(vis[x][y])
{
cout<<<<endl;
return ;
}
while(!q.empty())
{
pos u=q.front();
q.pop();
for(int i=;i<;i++)
{
pos th;
th.x=u.x+dx[i];
th.y=u.y+dy[i];
th.s=u.s+;
for(int i=;i<=u.s;i++)
th.move[i]=u.move[i];
th.move[th.s]=st[i];
if(th.x<||th.x>||th.y<||th.y>||vis[th.x][th.y])
continue;
vis[th.x][th.y]=;
if(th.x==x&&th.y==y)
{
cout<<th.s<<endl;
for(int j=;j<=th.s;j++)
cout<<th.move[j]<<endl;
return ;
}
q.push(th);
}
}
return ;
}