Data structure of BFS

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.