Princeton Alogorithm COS226 Week8 Shortest Path

shortest path is in an edge-weighted digrah, given an edge weighted digraph, find the shortest path from s to t.
application used shortest path below:


image.png

there are some variants in shortest path problem;

like which vertices?
single source: from one vertex s to every other vertex.
source-sink, from one vertex s to another t
all pairs, between all pairs of vertices.

restriction on edge weights,
non-negative weights, euclidean weights, arbitrary weights.

cycle,
no directed cycle, no "negative cycles"

api

image.png

image.png

image.png

edge relaxation

image.png
 private void relax(DirectedEdge e)
 {
 int v = e.from(), w = e.to();
 if (distTo[w] > distTo[v] + e.weight())
 {
 distTo[w] = distTo[v] + e.weight();
 edgeTo[w] = e;
 }
 }
image.png

Dijkstra

consider vertices in increasing order of distance from s (non-tree vertex with the lowest distTo[ ] value)
add vertex to tree and relax all edges pointing from that vertex


image.png

image.png

time complexity

image.png

shortest path in DAG

consider vertices in topological order, relax all edges pointing from that vertex;

image.png

image.png

longest path

image.png

image.png

add this implementation and visualization in extra credit

Bellman-Ford

when a graph which have negative edge will break the invariants in Dijkstra algorithm.
and the graph which have negative cycle will have no shortest path.

to handle both situation, we will use Bellman ford algorithm.


image.png

improvement

if distTo[v] does not change during pass i, no need to relax any edge pointing from v in pass i+1

so we can maintain queue of verices whose distTo[] changed.

the running time is still proportional to E * V in worst case, but much faster than that in practice


image.png

handle negative cycle

if there is a negative cycle, bellman-ford gets stuck in loop, updating distTo[] and edgeTo[] entries of vertices in the cycle.
if any vertex v is updated in phase V, there exists a negative cycle

arbitrage detection

image.png

add this implementation and visualization in extra credit
when we use improvement bellman ford, we could check one node into queue V times means there exists negative cycle.

QUIZ

Q1 Monotonic shortest path

image.png

the solution in this stackoverflow https://stackoverflow.com/questions/22876105/find-a-monotonic-shortest-path-in-a-graph-in-oe-logv
could only solve this problem when edge is all positive.
my solution is that (assumption edge weight is distinct)

  1. init every node except s, others are positive infinity. s = 0;
  2. sort the edges by weight in ascending order(when find increase path)
  3. considerate edge in this order, then check this edge can relax or not, if it could relax, relax it. if not, discard it. (if from point is positive infinity, failed to relax)
  4. then check is there a path reach the t.

now edge could have duplicate weight, how to handle it. below is a distinct edge weigh algorithm not handle case. because we need a strictly monotonic increasing path.

image.png

for every vertex we need to save two value, one is minPathSum, and secondPathSum, on above picture, the minPath is to third node is {6}, the second path is {3,4}
when we find a edge is same as min path edge weight, we need to check the second could build a possible relaxation.

Q2 Second shortest path

image.png

a naive wrong idea is that we compute the shortest path distances from s to every vertex and the shortest path distances from every vertex to t. and find the shortest path, we need to select a node which are not in the shortest path vertex, then find the minimum path in all of these node.

the correct way is that node could be same,but the path diff is that at least one edge is not same as the shortest path, so we need to select a edge which are not in the shortest path edge set. then use s to this edge from() , and this edge to() to t. find the minimum path.

Q3 Shortest path with one skippable edge

image.png

the idea is same as Q2, we precompute the shortest path from s to every vertex; compute the shortest path from every vertex to t. then we iterate every edge, check without this edge, what is minimum from s to this edge from(), and this edge to() to t.

Project Seam Carving

image.png

image.png

this project we need to keep the two two-dimension array, one is for picture another is for energy.

Start by writing the constructor as well as picture(), width() and height(). These should be very easy.

From there, write energy(). Calculating Δx^2 and Δy^2 are very similar. Using two private methods will keep your code simple. To test that your code works, use the client PrintEnergy described in the testing section above.

the core of this project is use topological sort to find the shortest path, but with the navie graph, we donot need to build a real graph object, we can define the two-dimension array as a graph


image.png

this is very similar with dynamic programming
one cell depend on its above three cells.

then for the improvement.

  • When finding a seam, call energy() at most once per pixel. For example, you can save the energies in a local variable energy[][] and access the information directly from the 2D array (instead of recomputing from scratch).
  • Avoid redundant calls to the get() method in Picture. For example, to access the red, green, and blue components of a pixel, call get() only once (and not three times).
  • The order in which you traverse the pixels (row-major order vs. column-major order) can make a big difference.
  • Creating Color objects can be a bottleneck. Each call to the get() method in Picture creates a new Color object. You can avoid this overhead by using the getRGB() method in Picture, which returns the color, encoded as a 32-bit int. The companion setRGB() method sets the color of a given pixel using a 32-bit int to encode the color.
  • Don’t explicitly transpose the Picture or int[][] until you need to do so. For example, if you perform a sequence of 50 consecutive horizontal seam removals, you should need only two transposes (not 100).
  • Consider using System.arraycopy() to shift elements within an array.
  • Reuse the energy array and shift array elements to plug the holes left from the seam that was just removed. You will need to recalculate the energies for the pixels along the seam that was just removed, but no other energies will change.

course quiz and project : https://github.com/yixuaz/algorithm4-princeton-cos226

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,482评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,377评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,762评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,273评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,289评论 5 373
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,046评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,351评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,988评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,476评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,948评论 2 324
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,064评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,712评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,261评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,264评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,486评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,511评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,802评论 2 345