计蒜客:一维座标的移动—bfs
题目描述:
在一个长度为 n 的座标轴上,蒜头君想从 A 点 移动到 B 点。他的移动规则如下:
向前一步,座标增加 1。
向后一步,座标减少 1。
跳跃一步,使得座标乘 2。
蒜头君不能移动到座标小于 0 或大于 n 的位置。蒜头想知道从 A 点移动到 B 点的最少步数是多少,你能帮他计算出来么?
输入格式
第一行输入 n, m 表示迷宫大小。(1≤n,m≤100)
接下来输入 n 行字符串表示迷宫,每个字符串长度为 m。(地图保证有且仅有一个终点,一个起始点)
输出格式
第一行输入三个整数 n,A,B,分别代表座标轴长度,起始点座标,终点座标。(50000≤A,B≤n≤5000)
样例输入
10 2 7
样例输出
3
解题思路:
这个比迷宫简直一毛一样,区别就是没有纵座标了,其他没什么区别,使用队列实现。
AC代码:
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <math.h>
#include <queue>
#include <vector>
using namespace std;
int n,a,b;
int vis[5005];//标记是否访问过
int dir(int x,int cnt)//向三个方向之一行走之后,更新座标值x
{
if(cnt==0)
x+=1;
else if(cnt==1)
x-=1;
else
x=x*2;
return x;
}
bool in(int x)//是否出界
{
return x>=0&&x<=n;
}
struct node
{
int x,step;//储存当前结点的座标以及当前步数
};
int bfs(int x)
{
int i;
node start,next;//start为起点的结点 ,next为下一个要遍历的结点
start.x=x;
start.step=0;
queue<node>q;
q.push(start);
vis[x]=1;
while(!q.empty())
{
node now=q.front();
q.pop();
for(i=0;i<3;i++)
{
int xx=dir(now.x,i);//xx为更新后的座标值
// cout<<"xx=="<<xx<<endl;
if(!in(xx)||vis[xx])//新的座标不符合情况
continue;
vis[xx]=1;
next.x=xx;
next.step=now.step+1;
if(xx==b)//注意:广搜,搜到即是最小值
return next.step;
q.push(next);
}
}
}
int main()
{
int i,j;
cin>>n>>a>>b;
cout<<bfs(a)<<endl;
return 0;
}