Recursion - Solving the Tower of Hanoi

Tower of Hanoi

insert image description here
Goal: Move one at a time. Move everything from A to C.
The big cannot be placed under the small.

Play online: http://www.htmleaf.com/Demo/201508272485.html
Likou (it's useless): https://leetcode-cn.com/problems/hanota-lcci/

recursive thinking

One: Put it directly on the target.
Two: put one in the cache first, and then put the second in the target.
. . .
N: Put all the above into the cache first, and then put them at the target.

To sum up:
1. Put the above into the cache.
2. Put me on the target.
3, put the cache in the target.

all code

Not much, but it looks winding.

//统计步数
let count = 0
//三个数组
let A = [5, 4, 3, 2, 1]
let B = []
let C = []
//打印状态
function printInfo() {
    
    
	console.log("A:" + A)
	console.log("B:" + B)
	console.log("C:" + C)
	console.log("=============================" + (++count))
}

//调用
han(A.length, A, C, B)

function han(n, from, to, middle) {
    
    
	//最上面的一个,直接push,pop,打印状态
	if (n === 1) {
    
    
		to.push(from.pop())
		printInfo()
		//下面的N个,三步走
	} else {
    
    
		han(n - 1, from, middle, to)
		han(1, from, to, middle)
		han(n - 1, middle, to, from)
	}
}

Effect: 5 elements require 31 steps.

insert image description here
8 elements require 255 steps.

insert image description here

Guess you like

Origin blog.csdn.net/qq_37284843/article/details/123921072