The width-First search algorithm (also known as breadth-first search) is one of the simplest algorithms for graph search, and this algorithm is also a prototype of many important graph algorithms. Dijkstra single-source Shortest path algorithm and prim minimum spanning tree algorithm both use the same idea as width-first search.
poj3278
Idea: root node N, n+1,n-1,2*n Three sub-nodes continue to extend, the target node K, looking for such a day shortest way
Code:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace Std;
struct node
{
int x;
int ans;
}Q[1000005];
int jx[]= { -1,1};
int n,k;
int map[1000005],v[1000005];
void BFs ()
{
struct node t,f;
int e=0,s=0;
T.x=n;
V[t.x]=1;
t.ans=0;
q[e++]=t;
while (S<e)
{
t=q[s++];
if (t.x==k)
{
printf ("%d\n", T.ans);
Break
}
for (int i=0; i<3; i++)
{
if (i==2)
f.x=t.x*2;
else F.x=t.x+jx[i];
if (!v[f.x]&&f.x>=0&&f.x<=100000)
{
f.ans=t.ans+1;
Q[e++]=f;
V[f.x]=1;
}
}
}
}
int main ()
{
while (scanf ("%d%d", &n,&k)!=eof)
{
memset (map,0,sizeof (map));
memset (v,0,sizeof (v));
BFS ();
}
return 0;
}
Data structure of BFS