我想在图表中找到从s到t的距离。如何更改bfs以查找距离或使用另一种具有良好O(n)
的算法。图表未加权和无向图非常重要
答案 0 :(得分:0)
您可以修改 BFS 以查找两个节点之间的(最短)距离。
使用此算法前需要注意的两个要点:
另一个需要注意的重要事项是:
1
,那么它会被推到后面,如果是 0
,则向前推<强> 实施 强>
此处, edges [v] [i] 是以对形式存在的邻接列表,即 edges [v] [i] .first 将包含连接v的节点和 edges [v] [i] .second 将包含v和 edge之间的距离[v] [i] .first。
Q是双端队列。距离是一个数组,其中距离[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);
}
}
}
}
}