Skip to content

Commit 146b760

Browse files
authored
Added TowerOfHanoi.js in Backtracking
1 parent 08d8c6b commit 146b760

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Backtracking/TowerOfHanoi.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
function towerOfHanoi(n, source, destination, auxiliary) {
2+
let moves = [] // will store all moves as [from, to]
3+
4+
// Recursive helper function
5+
function solve(disks, fromRod, toRod, auxRod) {
6+
// Base case: Only one disk left
7+
if (disks === 1) {
8+
moves.push([fromRod, toRod])
9+
return
10+
}
11+
12+
// Move n-1 disks from source to auxiliary
13+
solve(disks - 1, fromRod, auxRod, toRod)
14+
15+
// Move the largest disk from source to destination
16+
moves.push([fromRod, toRod])
17+
18+
// Move n-1 disks from auxiliary to destination
19+
solve(disks - 1, auxRod, toRod, fromRod)
20+
}
21+
22+
solve(n, source, destination, auxiliary)
23+
24+
return moves
25+
}
26+
27+
export { towerOfHanoi }

0 commit comments

Comments
 (0)