当前位置:网站首页>汉诺塔问题
汉诺塔问题
2022-07-31 01:38:00 【小卢要刷力扣题】
前言
给定一个数组arr,长度为N,arr中的值只有1,2,3三种
arr[i] == 1,代表汉诺塔问题中,从上往下第i个圆盘目前在左
arr[i] == 2,代表汉诺塔问题中,从上往下第i个圆盘目前在中
arr[i] == 3,代表汉诺塔问题中,从上往下第i个圆盘目前在右
那么arr整体就代表汉诺塔游戏过程中的一个状况
如果这个状况不是汉诺塔最优解运动过程中的状况,返回-1
如果这个状况是汉诺塔最优解运动过程中的状况,返回它是第几个状况
解题思路

7层汉诺塔问题的一个状态
最优解的第一个状态
全部盘子都在左边
第二个状态就是1号盘子在右边
第三个状态就是2号盘子在中间

i: 1~i的圆盘需要移动
F: 1~i的圆盘现在处在什么圆盘上,可能是左中右.
t:需要去的位置可能是左,中,右
other:除了from, to的另外一个位置

i层的圆盘没有任何道理是在other.上
如果index还在From上,说明第一大步没走完
第一步:1~i-1 从from到other
第二步:i从from到to
第三步:1~i-1从other到to
把每一步都用递归分解
最后相加,得出为第几步
代码
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;
}
}
边栏推荐
猜你喜欢

Teach you how to configure Jenkins automated email notifications

内网渗透——提权

MySql的安装配置超详细教程与简单的建库建表方法
![[WeChat applet] This article takes you to understand data binding, event binding, event parameter transfer, and data synchronization](/img/f8/8437783794c2007a74c0a153d85102.png)
[WeChat applet] This article takes you to understand data binding, event binding, event parameter transfer, and data synchronization

case语句的综合结果,你究竟会了吗?【Verilog高级教程】

35. 反转链表

"Real" emotions dictionary based on the text sentiment analysis and LDA theme analysis

GCC Rust获批将被纳入主线代码库,或将于GCC 13中与大家见面

"Actual Combat" based on part-of-speech extraction in the field of e-commerce and its decision tree model modeling

Shell 脚本循环遍历日志文件中的值进行求和并计算平均值,最大值和最小值
随机推荐
MySQL的分页你还在使劲的limit?
Xiaohei's leetcode journey: 117. Fill the next right node pointer of each node II
What is the ideal college life?
rpm安装postgresql12
tensorflow与GPU版本对应安装问题
九州云入选“可信云最新评估体系及2022年通过评估企业名单”
计算S=a+aa+…+aa…a
有没有可以做副业可以日入300元方法?
35. Reverse linked list
ROS Action communication
link与@import的区别
Mysql: Invalid default value for TIMESTAMP
Xiaohei's leetcode journey: 104. The maximum depth of a binary tree
TiDB 在多点数字化零售场景下的应用
coldfusion8后台计划任务拿shell
软件测试工作3年了,谈谈我是如何从刚入门进阶到自动化测试的?
.NET 跨平台应用开发动手教程 |用 Uno Platform 构建一个 Kanban-style Todo App
Ticmp - 更快的让应用从 MySQL 迁移到 TiDB
蓝牙mesh系统开发三 Ble Mesh 配网器 Provisioner
MySql的初识感悟,以及sql语句中的DDL和DML和DQL的基本语法