SPFA随手写,容易理解的

对应的图是



// spfa.cpp : Defines the entry point for the console application.

//


#include "stdafx.h"
#include <iostream>
#include <queue>
#include<vector>
using namespace std;
int graph[8][8];
#include<string>
bool visited[8];
int dis[8];
int pre[8];
void spfa(int graph[][8],int s,int e,int n)
{
memset(visited,false,sizeof(visited));
memset(dis,127,sizeof(dis));
memset(pre,0,sizeof(pre));
queue<int> q;
q.push(s);
visited[s]=true;
dis[s]=0;
while(!q.empty())
{
int top=q.front();
q.pop();
visited[top]=false;

for (int i=0;i<n;i++)
{
if (graph[top][i]!=0)
{
if (dis[i]>dis[top]+graph[top][i])
{
dis[i]=dis[top]+graph[top][i];
if(!visited[i])
{
   visited[i]=true;
    q.push(i);
}
}
}
}




}


for (int i=0;i<n;i++)
{
cout<<i<<"   "<<dis[i]<<endl;
}


}




int _tmain(int argc, _TCHAR* argv[])
{
memset(graph,0,sizeof(graph));
graph[0][1]=24;
graph[0][2]=8;
graph[0][3]=15;
graph[1][4]=6;
graph[2][4]=7;
graph[2][5]=3;
graph[3][6]=4;
graph[4][6]=9;
graph[5][6]=3;
graph[5][4]=2;
graph[6][1]=3;
spfa(graph,0,6,7);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值