This guide explains Hamiltonian Path & Cycle from first principles. The goal is to understand the problem it solves, why the algorithm works, how to implement it, and where it appears in real software systems.
What problem does it solve?
Hamiltonian Path & Cycle belongs to the graph-algorithm toolbox. Before coding, define what the vertices represent, what an edge means, and what result the system actually needs.
The core idea in simple terms
با Backtracking یک ترتیب معتبر از رأسها میسازیم و در بنبست انتخاب قبلی را برمیگردانیم.
Step-by-step process
- یک رأس شروع انتخاب میکنیم.
- یک همسایه استفادهنشده را امتحان میکنیم.
- در بنبست Backtrack میکنیم.
- اگر همه رأسها استفاده شدند مسیر پیدا شده است.
JavaScript example
function hamiltonian(graph) {
const nodes = Object.keys(graph);
function search(path, used) {
if (path.length === nodes.length) return path;
for (const v of graph[path.at(-1)] ?? []) if (!used.has(v)) {
used.add(v);
const r = search([...path,v], used);
if (r) return r;
used.delete(v);
}
return null;
}
for (const s of nodes) { const r = search([s], new Set([s])); if (r) return r; }
return null;
}Real-world and workplace examples
- برنامهریزی بازدید بدون تکرار
- Graph Puzzle
- Route Sequencing
- مبنای ساختاری TSP
Time and space complexity
در حالت ساده نمایی و about O(V!)
When should you use it?
Use it when the problem matches this condition: وقتی هر رأس باید دقیقاً یک بار بازدید شود.
When is it not a good fit?
It is usually not the best choice when: برای گراف بزرگ brute force عملی نیست..
Summary
Do not choose an algorithm by name alone. First identify whether the graph is directed or undirected, weighted or unweighted, and whether the goal is traversal, reachability, shortest path, connectivity, spanning structure, or combinatorial optimization.