计蒜客一维坐标的移动

xiaoxiao2021-02-28  41

使用广搜bfs,算出每次加1,减1,乘2的值,并用队列存储,在这样循环3次之后,该值退出队列,开始计算下一个值,直到寻找到该值

ac代码:

#include<iostream> #include<queue> #include<cstdio> using namespace std; int n,A,B,flag=0; int temp[5001]; bool vis[5001]={false}; struct Point{ int x,step; Point(int _x,int _step): x(_x),step(_step){} }; bool in(int x) { return x>=0&&x<=n; } int bfs(int sx) { queue<Point> q; int step; vis[sx]=true; q.push(Point(sx,1)); while(!q.empty()) { int x=q.front().x; step=q.front().step; int dir[3]={1,-1,x}; for(int i=0;i<3;i++) { int tx=x+dir[i]; if(in(tx)) { if(!vis[tx]) { vis[tx]=true; q.push(Point(tx,step+1)); } if(tx==B) { flag=1; break; } } } q.pop(); if(flag==1) break; } return step; } int main() { //freopen("1.txt","r",stdin); cin>>n>>A>>B; cout<<bfs(A); return 0; }
转载请注明原文地址: https://www.6miu.com/read-2624864.html

最新回复(0)