計蒜客:一維座標的移動—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;
}