A* 탐색

A* search

지금까지의 비용과 목표까지의 추정 비용을 합쳐 다음 칸을 고릅니다.

···
html
<div class="v"><header><b>A* GRID</b><span id="state"></span></header><main><div class="agrid" id="agrid"></div><div class="acost" id="acost"></div></main><footer>frontier ordered by f = g + h</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} .agrid{height:78%;display:grid;grid-template-columns:repeat(5,1fr);grid-template-rows:repeat(4,1fr);gap:2px;max-width:230px;margin:auto}.agrid b{border:1px solid var(--line);border-radius:3px;display:grid;place-items:center;font:700 .72em ui-monospace,monospace}.agrid b.wall{background:var(--line)}.agrid b.path{background:color-mix(in srgb,var(--accent) 25%,var(--surface))}.acost{text-align:center;color:var(--accent);font:600 .78em ui-monospace,monospace}
js
const route=[0,1,2,7,12,13,14,19],walls=[6,11,16];let step=0;function draw(){const at=route[step],x=at%5,y=Math.floor(at/5),g=step,h=Math.abs(4-x)+Math.abs(3-y);document.getElementById("agrid").innerHTML=Array.from({length:20},(_,i)=>"<b class='"+(walls.includes(i)?"wall":i===at?"active":route.slice(0,step).includes(i)?"path":"")+"'>"+(i===0?"S":i===19?"G":i===at?"•":"")+"</b>").join("");document.getElementById("acost").textContent="g "+g+" + h "+h+" = f "+(g+h);document.getElementById("state").textContent="expand "+(step+1)+" / "+route.length;step=(step+1)%route.length}draw();setInterval(draw,720)

A*는 시작점에서 각 후보까지의 실제 비용 g와 목표까지의 추정 비용 h를 더한 f=g+h가 가장 작은 후보를 먼저 살핍니다. 이웃에 더 짧은 경로를 발견하면 후보의 비용과 부모를 갱신합니다.

h가 실제 남은 비용을 넘지 않는 허용적 휴리스틱이면 최적 경로를 찾을 수 있습니다. 휴리스틱이 너무 약하면 다익스트라 탐색처럼 많은 칸을 살피고, 너무 크게 잡으면 최적성을 잃을 수 있습니다.

언제 쓰나

지도나 게임 격자에서 목표 방향을 이용해 경로를 빠르게 찾을 때 씁니다.

페이지로 열기 ↗