[英]Dijkstra shortest path on multiple unweighted graphs?
根據原始圖創建一個新的加權圖,其中藍色 -> 紅色路徑花費 3 而不是 1,然后在其上運行 Dijkstra。
編輯:可能沒有必要實際創建新圖表,您可以直接從原始圖表中獲取權重,但首先創建新圖表可能更容易遵循。
頂角看起來像這樣:
A ← 3 → B ← 1 → C ← 1 → D ...
↑ ↑ ↑
1 1 3
↓ ↓ ↓
E ← 3 → F ← 3 → G...
這只是標准的 Dijkstra。
// Not pure C++
enum Color { Red, Blue};
using Graph = std::vector_like<std::vector_like<Color>>;
using Point = std::pair<int, int>;
int getCost(Graph const& graph, Point src, Point dst)
{
// Assumes: src and dst are 1 point away from each other.
// This assumes that work is done via
// getListOfPointsReachable() which only gets nodes
// nodes that are adjecent.
//
// Standard movement cost.
int cost = 1;
// Add a cost if switching between blue red.
if (graph[src] != graph[dst]) {
cost += 2;
}
return cost;
}
void Dijkstra(Graph const& graph, Point start, Point end)
{
std::set<Point> visited;
// Boundary: int => Cost
// Point => Point cost applies to.
// Using tuple as it already has the comparison operator defined.
using Boundary = std::tuple<int, Point>;
std:: priority_queue<Boundary> boundary;
// Set up the boundary list with a start.
boundary.emplace(0, start);
while (!boundary.empty())
{
Boundary next = boundry.top();
boundary.pop();
int cost = std::get<0>(next);
Point nextP = std::get<1>(next);
if (nextP == end)
{
throw std::runtime_error("Found route to end: Cheapest Route is: " + cost);
}
if (visited.find(nextP) != std::end(visited))
{
// we already did this node.
continue;
}
visited.insert(nextP);
std::list<Point> dests = getListOfPointsReachable(graph, nextP);
for (auto const& dest: dests)
{
int extraCost = getCost(graph, nextP, dest);
boundary.emplace(extraCost + cost, dest);
}
}
throw std::runtime_error("No Route from Start to End");
}
要創建圖形,請使用此偽代碼在節點之間添加邊
AddEdge( n1, n2 )
SET cost = 1
IF n1color != n2color
SET cost = 3;
graph.AddEdge( n1, n2, cost );
RUN Dijsktra on graph
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.