In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:
(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto another tower.
(3) A disk cannot be placed on top of a smaller disk.
Write a program to move the disks from the first tower to the last using stacks.
Example1:
Input: A = [2, 1, 0], B = [], C = []
Output: C = [2, 1, 0]
Example2:
Input: A = [1, 0], B = [], C = []
Output: C = [1, 0]
Note:
A.length <= 14
Solutions
Solution 1: Recursion
We design a function $dfs(n, a, b, c)$, which represents moving $n$ disks from $a$ to $c$, with $b$ as the auxiliary rod.
First, we move $n - 1$ disks from $a$ to $b$, then move the $n$-th disk from $a$ to $c$, and finally move $n - 1$ disks from $b$ to $c$.
The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Here, $n$ is the number of disks.
/** Do not return anything, modify C in-place instead. */functionhanota(A:number[],B:number[],C:number[]):void{constdfs=(n:number,a:number[],b:number[],c:number[])=>{if(n===1){c.push(a.pop()!);return;}dfs(n-1,a,c,b);c.push(a.pop()!);dfs(n-1,b,a,c);};dfs(A.length,A,B,C);}
We can use a stack to simulate the recursive process.
We define a struct $Task$, which represents a task, where $n$ represents the number of disks, and $a$, $b$, $c$ represent the three rods.
We push the initial task $Task(len(A), A, B, C)$ into the stack, and then continuously process the task at the top of the stack until the stack is empty.
If $n = 1$, then we directly move the disk from $a$ to $c$.
Otherwise, we push three subtasks into the stack, which are:
Move $n - 1$ disks from $b$ to $c$ with the help of $a$;
Move the $n$-th disk from $a$ to $c$;
Move $n - 1$ disks from $a$ to $b$ with the help of $c$.
The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Here, $n$ is the number of disks.
/** Do not return anything, modify C in-place instead. */functionhanota(A:number[],B:number[],C:number[]):void{conststk:any[]=[[A.length,A,B,C]];while(stk.length){const[n,a,b,c]=stk.pop()!;if(n===1){c.push(a.pop());}else{stk.push([n-1,b,a,c]);stk.push([1,a,b,c]);stk.push([n-1,a,c,b]);}}}