-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathTowerOfHanoi.js
More file actions
27 lines (20 loc) · 682 Bytes
/
TowerOfHanoi.js
File metadata and controls
27 lines (20 loc) · 682 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function towerOfHanoi(n, source, destination, auxiliary) {
let moves = [] // will store all moves as [from, to]
// Recursive helper function
function solve(disks, fromRod, toRod, auxRod) {
// Base case: Only one disk left
if (disks === 1) {
moves.push([fromRod, toRod])
return
}
// Move n-1 disks from source to auxiliary
solve(disks - 1, fromRod, auxRod, toRod)
// Move the largest disk from source to destination
moves.push([fromRod, toRod])
// Move n-1 disks from auxiliary to destination
solve(disks - 1, auxRod, toRod, fromRod)
}
solve(n, source, destination, auxiliary)
return moves
}
export { towerOfHanoi }