← Semua pelajaran
Cara kerja pencarian graph
Graph sama, queue atau stack
bfs.js
function bfs(graph, start) { const queue = [start]; const seen = new Set([start]); // baca dari depan pakai index: O(1), beda dengan shift() for (let head = 0; head < queue.length; head++) { const node = queue[head]; // yang paling lama dulu: node terdekat keluar duluan visit(node); for (const next of graph[node]) { if (seen.has(next)) continue; seen.add(next); queue.push(next); } }}dfs.js
function dfs(graph, start) { const stack = [start]; const seen = new Set(); while (stack.length) { const node = stack.pop(); // yang paling baru dulu: terus masuk lebih dalam if (seen.has(node)) continue; seen.add(node); visit(node); // dibalik, supaya tetangga pertama di-pop duluan for (const next of [...graph[node]].reverse()) { if (!seen.has(next)) stack.push(next); } }}Gambar tembok, lalu cari cuma BFS yang menjamin jalur terpendek
Grid Klik sel untuk memasang atau melepas tembok
panjang jalur
sel dikunjungi
Terpendek menurut jumlah edge. Kalau edge punya bobot, misalnya jarak jalan, kamu butuh Dijkstra
path.js
// catat siapa yang menemukan tiap selparent.set(next, node); // telusuri balik dari tujuan ke awalconst path = [];for (let at = goal; at !== undefined; at = parent.get(at)) { path.unshift(at);}Topik
Berikutnya: Cara kerja transaction database
Buka pelajaran