BFS and SPFA, the difference between the shortest path algorithm, details

Source: Internet
Author: User

SPFA is very similar in form and BFS, except that one point in BFS is impossible to re-enter the queue, but SPFA
One point may be placed in the queue again after the queue, that is, after a point has improved the other points, after a period of time may be the
The body is improved, and then used again to refine the other points so that they are repeated iteratively.

Determine if there is a negative loop: If a point enters the queue more than V, there is a negative loop (SPFA cannot process the graph with negative loops).

The need to remember is that it is a different topic, perhaps with SPFA (more than a vis[u]=0) will time out, may also use SPFA more worry, so be flexible.

int BFS (int s)
{
	memset (vist,0,sizeof (vist));
	memset (dist,0x3f,sizeof (Dist));
	int u,v; 
	queue<int>q;
	Vist[s]=1;  
	dist[s]=0;
	Q.push (s);
	while (!q.empty ())
	{
		u=q.front ();
		Q.pop ();
		for (int i =head[u]; I!=-1 i=edge[i].next)
		{
			v=edge[i].v;
			  if (Dist[v] > Dist[u]+edge[i].c)
			  {
			  	     
  			  	     dist[v] = dist[u]+edge[i].c;
			  	     if (!vist[v])
			  	     {
			  	        vist[v]=1;
					 Q.push (v);
	}}} return 0;
}


int SPFA (int s)
{
	memset (vist,0,sizeof (vist));
	memset (dist,0x3f,sizeof (Dist));
  	int u,v; 
	queue<int>q;
	Vist[s]=1;  
	dist[s]=0;
	Q.push (s);
	while (!q.empty ())
	{
		u=q.front ();
		Q.pop ();
		vist[u]=0;//difference in this for
		(int i =head[u]; I!=-1 i=edge[i].next)
		{
			v=edge[i].v;
			  if (Dist[v] > Dist[u]+edge[i].c)
			  {
			  	     
  			  	     dist[v] = dist[u]+edge[i].c;
			  	     if (!vist[v])
			  	     {
			  	        vist[v]=1;
					Q.push (v);
	}}} return 0;
}

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.