Dijkstra shortest path

다익스트라 최단 경로

Settle the cheapest current candidate when edge weights are nonnegative.

···
html
<div class="v"><header><b>DIJKSTRA</b><span id="state"></span></header><main><div class="route" id="route"></div><div class="dist" id="dist"></div></main><footer>relax neighbors, then settle</footer></div>
css
.v{width:min(92vw,660px);height:min(86vh,310px);box-sizing:border-box;padding:clamp(9px,2.5vmin,18px);border:1px solid var(--line);border-radius:14px;background:var(--surface);display:flex;flex-direction:column;gap:7px;color:var(--fg);font:500 clamp(15px,4.5vmin,19px)/1.25 var(--font-sans, sans-serif)}.v header,.v footer{display:flex;justify-content:space-between;align-items:center;gap:8px;white-space:nowrap}.v header b{color:var(--accent);font-size:.9em}.v header span,.v footer{color:var(--muted);font-size:.82em}.v main{flex:1;min-height:0;position:relative;overflow:hidden}.v .mono{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.v .active{background:var(--accent)!important;color:var(--bg)!important;border-color:var(--accent)!important}.v .muted{opacity:.45} .route{height:57%;display:flex;justify-content:space-around;align-items:center}.route b{border:1px solid var(--line);border-radius:50%;width:31px;height:31px;display:grid;place-items:center}.route em{color:var(--muted);font-style:normal}.dist{text-align:center;font:600 .9em ui-monospace,monospace;color:var(--accent)}
js
let n=0;const names=["A","B","C","D"],dist=[[0,"∞","∞","∞"],[0,2,5,"∞"],[0,2,3,6],[0,2,3,4]];function draw(){document.getElementById("route").innerHTML=names.map((x,i)=>"<b class=\""+(i===n?"active":i>n?"muted":"")+"\">"+x+"</b>"+(i<3?"<em>→</em>":"")).join("");document.getElementById("dist").textContent=names.map((x,i)=>x+":"+dist[n][i]).join("  ");document.getElementById("state").textContent="settle "+names[n];n=(n+1)%4}draw();setInterval(draw,1000)

Dijkstra’s algorithm starts with distance zero at the source and repeatedly settles the unsettled node with the smallest tentative distance. It relaxes neighbors whenever a shorter route appears.

A settled distance stays final only when edge weights are nonnegative. Negative edges require a different algorithm.

When to use

Use it for least-cost paths when edge weights cannot be negative.

Open as page ↗