BFS+ print path

The title is to give you the starting point sx and the ending point gx; the cow can perform the following two operations at the starting point:

Walk: John spends one minute moving from any point X to point X-1 or point X+1.

Teleport: John spends one minute moving from any point X to point 2*X.

You want to output the shortest steps and print the path.

The shortest number of steps is to use bfs.

As for the path, you can use a structure to store the parent node of each point, and then recursively output the path.

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
#define MAX 100010
int sx,gx,ans;
struct mask
{
    mask(int x,int step):x(x),step(step){};
    int x,step,f;
};/
struct node
{
    int x;
}p[MAX];//保存父节点
queue<mask>q;
int dx[]={1,-1};
int flag=0;
bool vis[MAX];
bool check(int r)
{
    return (0<=r&&r<=MAX);
}
void bfs()
{
    flag=0;
    while(!q.empty())q.pop();
   q.push(mask(sx,0));
   memset(vis,false,sizeof(vis));
   vis[sx]=true;//printf("%d\n",q.front());
   while(q.size())
   {
      mask tmp=q.front();q.pop();
     // printf("ok\n");
      if(tmp.x==gx)
      {
          ans=tmp.step;
          flag=1;
          break;
      }
      for(int i=0;i<2;i++)
      {
          int nx=tmp.x+dx[i];
          if(check(nx)&&!vis[nx])
          {
              vis[nx]=true;
              p[nx].x=tmp.x;
              q.push(mask(nx,tmp.step+1));
          }
      }
      int nx1=tmp.x*2;
      if(check(nx1)&&!vis[nx1])
          {
              vis[nx1]=true;
                p[nx1].x=tmp.x;
              q.push(mask(nx1,tmp.step+1));
          }
   }
}
void pri(int x1)
{
    if(x1==sx){
        printf("%d ",sx);
        return  ;
    }
    pri(p[x1].x);
    printf("%d ",x1);
}
int main()
{
    while(~scanf("%d %d",&sx,&gx)){
     if(sx==-1&&gx==-1)break;
     bfs();
       if(flag)
         printf("%d\n",ans);
        else printf("-1\n");
        pri(gx);
        printf("\n");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325234942&siteId=291194637