当前位置:网站首页>Tower of Hanoi problem
Tower of Hanoi problem
2022-07-31 01:48:00 【Xiao Lu wants to brush the force and deduct the question】
前言
给定一个数组arr,长度为N,arr中的值只有1,2,3三种
arr[i] == 1,代表汉诺塔问题中,从上往下第i个圆盘目前在左
arr[i] == 2,代表汉诺塔问题中,从上往下第i个圆盘目前在中
arr[i] == 3,代表汉诺塔问题中,从上往下第i个圆盘目前在右
那么arr整体就代表汉诺塔游戏过程中的一个状况
如果这个状况不是汉诺塔最优解运动过程中的状况,返回-1
如果这个状况是汉诺塔最优解运动过程中的状况,返回它是第几个状况
解题思路
7A state of the Layer Tower of Hanoi problem
The first state of the optimal solution
All plates are on the left
The second state is1Plate No. is on the right
The third state is2The plate is in the middle
i: 1~iThe disc needs to be moved
F: 1~iOn what disk is the disk of ,Possibly left-center-right.
t:The place to go may be left,中,右
other:除了from, toanother location
iThe layer of the disc doesn't make any sense at allother.上
如果index还在From上,Explain that the first big step is not over
第一步:1~i-1 从from到other
第二步:i从from到to
第三步:1~i-1从other到to
Break down each step with recursion
最后相加,get the first step
代码
public static int kth(int[] arr) {
int N = arr.length;
return step(arr, N - 1, 1, 3, 2);
}
// 0...index这些圆盘,arr[0..index] index+1层塔
// 在哪?from 去哪?to 另一个是啥?other
// arr[0..index]这些状态,是index+1层汉诺塔问题的,最优解第几步
public static int step(int[] arr, int index, int from, int to, int other) {
if (index == -1) {
return 0;
}
if (arr[index] == other) {
return -1;
}
// arr[index] == from arr[index] == to;
if (arr[index] == from) {
return step(arr, index - 1, from, other, to);
} else {
int p1 = (1 << index) - 1;
int p2 = 1;
int p3 = step(arr, index - 1, other, to, from);
if (p3 == -1) {
return -1;
}
return p1 + p2 + p3;
}
}
边栏推荐
- 类似 MS Project 的项目管理工具有哪些
- 软件测试缺陷报告---定义,组成,缺陷的生命周期,缺陷跟踪产后处理流程,缺陷跟踪处理流程,缺陷跟踪的目的,缺陷管理工具
- 数字图像隐写术之JPEG 隐写分析
- Overview of prometheus monitoring
- JPEG Steganalysis of Digital Image Steganography
- 设置浏览器滚动条样式
- Meta元宇宙部门第二季度亏损28亿 仍要继续押注?元宇宙发展尚未看到出路
- MySQL stored procedure
- Gateway routing configuration
- 【genius_platform软件平台开发】第七十四讲:window环境下的静态库和动态库的一些使用方法(VC环境)
猜你喜欢
随机推荐
VSCode Plugin: Nested Comments
软件测试缺陷报告---定义,组成,缺陷的生命周期,缺陷跟踪产后处理流程,缺陷跟踪处理流程,缺陷跟踪的目的,缺陷管理工具
1.非类型模板参数 2.模板的特化 3.继承讲解
What have I experienced when I won the offer of BAT and TMD technical experts?
case语句的综合结果,你究竟会了吗?【Verilog高级教程】
12 pictures take you to fully understand service current limit, circuit breaker, downgrade, and avalanche
C language applet -- common classic practice questions
uniapp使用第三方字体
JPEG Steganalysis of Digital Image Steganography
934. 最短的桥
有没有可以做副业可以日入300元方法?
Nacos
初识C语言 -- 数组
Xiaohei's leetcode journey: 104. The maximum depth of a binary tree
934. The Shortest Bridge
基于FPGA的图像实时采集
Between two orderly array of additive and Topk problem
MySQL的存储过程
PDF split/merge
【genius_platform软件平台开发】第七十四讲:window环境下的静态库和动态库的一些使用方法(VC环境)