Depth-first search

깊이 우선 탐색

Follow one branch to its end, then backtrack to explore another.

···
html
<div class="v"><header><b>DEPTH-FIRST SEARCH</b><span id="state"></span></header><main><div class="dbranches" id="dbranches"></div><div class="dstack" id="dstack"></div></main><footer>descend → backtrack → descend</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} .dbranches{height:68%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px}.drow{display:flex;align-items:center;justify-content:center;gap:clamp(4px,2vw,15px)}.drow b{width:clamp(22px,6vmin,40px);height:clamp(22px,6vmin,40px);border:1px solid var(--line);border-radius:50%;display:grid;place-items:center;font:700 .8em ui-monospace,monospace}.drow i{width:clamp(8px,2vw,22px);height:2px;background:var(--line)}.dstack{text-align:center;color:var(--accent);font:600 .78em ui-monospace,monospace}
js
const stages=[{at:"A",stack:"A"},{at:"B",stack:"A → B"},{at:"D",stack:"A → B → D"},{at:"C",stack:"A → C"},{at:"E",stack:"A → C → E"}];let step=0;function row(names,at,visited){return "<div class=drow>"+names.map((v,i)=>"<b class='"+(v===at?"active":visited.includes(v)?"muted":"")+"'>"+v+"</b>"+(i<2?"<i></i>":"")).join("")+"</div>"}function draw(){const s=stages[step],visited=stages.slice(0,step).map(x=>x.at);document.getElementById("dbranches").innerHTML=row(["A","B","D"],s.at,visited)+row(["A","C","E"],s.at,visited);document.getElementById("dstack").textContent="stack: "+s.stack;document.getElementById("state").textContent=step===3?"backtrack":"visit "+s.at;step=(step+1)%stages.length}draw();setInterval(draw,900)

Depth-first search follows an unvisited neighbor until it reaches a dead end, then backtracks through a call stack or explicit stack.

Without a visited set, cycles can repeat forever. Unlike breadth-first search, DFS does not directly guarantee a minimum-hop path in an unweighted graph.

When to use

Use it for connected components, cycle checks, and backtracking search.

Open as page ↗