题目链接https://nanti.jisuanke.com/t/44820
题目太长就不放了,大概意思是,给你光标的现在位置和目标位置,问你最短多少步能到达目标位置。
运用算法:bfs
注意:我觉得bfs重点就在于判断条件这里一定要思路清晰。
具体看代码,代码有注释。
AC代码:
#include<cstdio>
#include<string>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<map>
#include<ctime>
#include<queue>
using namespace std;
int num[130];//记录每行的长度
int vis[130][90];//标记是否走过此格
int dis[10][2] = {-1,0,0,-1,0,1,1,0};//上下左右四个点
int res = -1;
int nx,ny;//目标点
int n;
struct node{
int x,y;
int cnt = 0;
}f[10];
bool check(int &x,int &y)
{
if(x < 1||x > n||vis[x][y] == 1)return true;
else return false;
}
queue<node>q;
int bfs()
{
node pre;
while(!q.empty())
{
pre = q.front();
q.pop();
node now;
for(int i = 0;i < 4;i++)
{
now.x = pre.x+dis[i][0];
now.y = pre.y+dis[i][1];
if(dis[i][0]!=0) //上下走
{
if(now.x >= 1&&now.x <= n&&now.y > num[now.x])
{
now.y = num[now.x];
}
}
else if(dis[i][1]!=0) //左右走
{
if(now.y == num[now.x]+1&&now.x >= 1&&now.x <= n)
{
now.x++;
if(now.x >= 1&&now.x <= n)now.y = 0;
}
else if(now.y == -1&&now.x >= 1&&now.x <= n)
{
now.x--;
if(now.x >= 1&&now.x <= n)now.y = num[now.x];
}
}
if(check(now.x,now.y))
{
continue;
}
vis[now.x][now.y] = 1;
now.cnt = pre.cnt+1;
if (now.x == nx&&now.y == ny)//判断是否找到目标点
{
res = now.cnt;
break;//根据队列先进先出的性质,找到的第一个点就是最步数
}
q.push(now);
}
if(res!=-1)break;
}
}
int main()
{
int t;
scanf/("%d",&t);
while(t--)
{
res = -1;
memset(vis,0,sizeof(vis)); //初始化标记数组
scanf("%d",&n);
for(int i = 1 ; i <= n;i++)
{
scanf("%d",&num[i]);
}
scanf("%d %d",&f[0].x,&f[0].y);
scanf("%d %d",&nx,&ny);
//以上是输入
vis[f[0].x][f[0].y] = 1;
q.push(f[0]);
if(f[0].x == nx&&f[0].y == ny)//如果初始点即为目标点时
{
printf("0\n");
}
else
{
bfs();
printf("%d\n",res);
}
while(!q.empty())//清空队列
{
q.pop();
}
}
return 0;
}