[英]Finding all the shortest paths between two nodes in unweighted undirected graph
[英]Find distance between two nodes in an undirected and unweighted graph
我想在图中找到从s到t的距离。 我如何更改bfs以查找距离或使用具有良好O(n)
另一种算法。 准确地对图进行加权和无向很重要
您可以修改BFS以找到两个节点之间的(最短)距离。
使用此算法之前需要注意的两个要点:
另一个要注意的重要事项是:
1
,则将其向后推,如果为0
,则向前推。 实作
在这里, edges [v] [i]是成对存在的邻接表,即edges [v] [i] .first将包含v所连接的节点, edges [v] [i] .second将包含v首先包含v和edges [v] [i]之间的距离。
Q是一个双端队列 。 distance是一个数组,其中distance [v]将包含从起始节点到v节点的距离。 最初,从源节点到每个节点定义的距离是无穷大。
void bfs (int start)
{
deque <int > Q; //Double-ended queue
Q.push_back( start);
distance[ start ] = 0;
while( !Q.empty ())
{
int v = Q.front( );
Q.pop_front();
for( int i = 0 ; i < edges[v].size(); i++)
{
/* if distance of neighbour of v from start node is greater
than sum of distance of v from start node and edge weight between v and its neighbour
(distance between v and its neighbour of v) ,then change it */
if(distance[ edges[ v ][ i ].first ] > distance[ v ] + edges[ v ][ i ].second )
{
distance[ edges[ v ][ i ].first ] = distance[ v ] + edges[ v ][ i ].second;
/*if edge weight between v and its neighbour is 0 then push it to front of
double ended queue else push it to back*/
if(edges[ v ][ i ].second == 0)
{
Q.push_front( edges[ v ][ i ].first);
}
else
{
Q.push_back( edges[ v ][ i ].first);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.