bfs和spfa最短路演算法的區別,細節

來源:互聯網
上載者:User

SPFA  在形式上和BFS非常類似,不同的是BFS中一個點出了隊列就不可能重新進入隊列,但是SPFA中
一個點可能在出隊列之後再次被放入隊列,也就是一個點改進過其它的點之後,過了一段時間可能本
身被改進,於是再次用來改進其它的點,這樣反覆迭代下去。

判斷有無負環:如果某個點進入隊列的次數超過V次則存在負環(SPFA無法處理帶負環的圖)。

 

而需要記住的是,又是不同的題目,也許用spfa(多了 一個vis[u]=0)會逾時,也可能用spfa更憂;所以要隨時變通。

 

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;//差別在這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;}

 

 

 

 
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.