


























A good way to think about Dijkstra is:
Dijkstra works when the first time you remove a node from the priority queue, you already know its optimal value.
This is called the greedy property.
If a node's value can still improve later by taking a different path, Dijkstra is not applicable.
Edges represent distances.
Suppose we're finding the shortest path from A.
Initially
We pop B first because 2 < 5.
Could there later be another path to B shorter than 2?
No.
Any other path must go through C, whose distance is already ≥5.
So
Impossible to improve.
This is exactly why Dijkstra works.
Requirement:
Total latency
Again,
Perfect for Dijkstra.
Road lengths
Distance always accumulates positively.
Works.
Edge
Cost
Again additive positive cost.
Works.
Suppose bandwidths
Path capacity is
So
We maximize the minimum.
A modified Dijkstra works because
The capacity never increases after extending a path.
The greedy property still holds.
Initially
Dijkstra pops
But later
Much better.
Too late.
Greedy fails.
Bellman-Ford is needed.
Products
vs
Notice
looked optimal initially
but later became
Dijkstra finalized B too early.
Suppose
Longest path
vs
Again
looked finished
but wasn't.
Exactly your interview problem.
Products may increase dramatically later.
Greedy property breaks.
Imagine
Objective
Reaching a node cheaply isn't necessarily best if another path collects much more reward.
No greedy property.
Suppose your path value is
Ask:
Can extending a worse path ever make it better than a currently better path?
If the answer is No, Dijkstra usually works.
If Yes, Dijkstra usually fails.
with
Cannot decrease.
Works.
Cannot increase.
Works.
Cannot decrease in the relevant direction.
Works.
because
A worse partial product
can become
while the better one
becomes
Ordering changes.
A worse partial sum can become better.
Ordering changes.
When solving a graph problem, ask these questions:
distance += edgecost += edgetime += edgeFor example, suppose two paths reach different nodes with current values:
If after one more edge you can get:
then the ordering has flipped. Once this can happen, the greedy assumption behind Dijkstra no longer holds, and you should be suspicious of using it.
This "can the ordering flip?" test is one of the quickest ways to judge whether Dijkstra is appropriate in an interview.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。